C
C#4mo ago
Steadhaven

IDisposable and using keyword?

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

public interface ICarnivore {}

public class Wolf : ICarnivore, IDisposable {
public void Dispose() {}
}
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 :) )
3 Replies
reflectronic
reflectronic4mo ago
you can implement IDisposable on any class, yes. no, the Dispose method is not 'automatically run'. it is just a regular method like any other method
TheBoxyBear
TheBoxyBear4mo ago
1 - Mostly correct (explained below) 2- When an object goes out of scope with no remaining references, it gets picked up by the garbage collector. The object may however be using unmanaged resources not known to the garbage collector that need releasing. You can specify the freeing of these in the finalizer but you might also want to dispose of these resources early as the garbage collector doesn't immediately kick in when an object is prime for deletion. This is what IDisposable is for. It's common practice to dispose within the finalizer but having it as a separate method allows for the manual early disposal. 3 - using in this context is syntax sugar for automatically disposing of an object at a certain time. With the old bracket syntax as shown in your snippet, it creates a scope for the disposable object and calls dispose when exiting that scope. The new syntax ending in a semicolon after the declaration, the disposing is tied to the current scope.
FusedQyou
FusedQyou4mo ago
FYI, using is lowered into a try-finally, in which the finally block calls the dispose method of a class. IDisposable is a generalized way to free unmanaged resources and internally a lot of things assume that the class will implement it if something must be disposed. Also, using (Wolf wolf = new Wolf()) {} exists but another variant is using Wolf wolf = new Wolf;. The difference is the removal of an indent and instead the compiler guesses when the class should be disposed. I believe this is usually done after the last line using a disposable class.