C#C
C#2y ago
Steadhaven

IDisposable and using keyword?

using (Wolf wolf = new Wolf()) {}

public interface ICarnivore {}

public class Wolf : ICarnivore, IDisposable {
   public void Dispose() {}
}

I am trying to understand using and IDisposable.

It seems that we can attach IDisposable to any class, which gives us a method called Dispose that we have to implement. This dispose method is automatically run and does whatever is specified, whenever we shutdown/remove a class.

And using is something we use for IDisposable classes only it seems. And somehow the using keyword would then know what to do when we shutdown the class...

1- I can kind of understand IDisposable, but want to know if my explanation is correct
2- What does it mean that a class is shutdown/removed? how can I do this in code?
3- the using keyword (as I tried to explain above) still make almost no sense, and I am even sensing it can be used without IDisposable

(If needed for other language examples then I know Java/Scala/React a bit, but prefer C# explanation :) )
Was this page helpful?