If a class has an instance field that implements IDisposable then the containing class implements IDisposable and class that fields Dispose method from within its Dispose method.
public class A : IDisposable
{
public System.Drawing.Font font = new Font("Arial", 10.0f);
public void Dispose()
{
font.Dispose()
}
}
(I know I didn't do the dispose pattern correctly, but for sample code should be good enough)
If the field is a static field though where should the call to the field's Dispose be?
public class B
{
public static System.Drawing.Font font = new Font("Arial", 10.0f);
}
I could make class B implement IDisposable and have that call font.Dispose
but if B.font is used again later on that would cause problems. As well as you'd have to remember that dispise accessing a static method you need to create an instance just to call Dispose.
I could also make a static Dispose method but then users have to remember to call Dispose and have to make sure they're the last user of it in the program.
You can have the Dispose method in a singleton class but not in a static class.
Singletons are generally speaking alive for the lifetime of a process / AppDomain . If you find yourself wanting to Dispose them then you probably need to refactor your solution a bit.
The Dispose method is automatically called when a using statement is used. All the objects that can implement the IDisposable interface can implement the using statement. You can use the ildasm.exe tool to check how the Dispose method is called internally when you use a using statement.
The Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object. Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer. If the type has no finalizer, the call to GC.
Static fields are initialised when the type is loaded.
Therefore it logically it makes sense to dispose the object assigned to the static field when the containing type is unloaded.
However, types are not unloaded. There may be some exotic complication here around AppDomains, but I suspect that doesn't apply in your case.
Therefore I wouldn't dispose the instance, otherwise you will have a publicly available instance of an object that is unfit for use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With