Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disposing an IDisposable object stored in a public static field

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.

like image 538
shmuelie Avatar asked Dec 25 '12 18:12

shmuelie


People also ask

Can static class be Dispose C#?

You can have the Dispose method in a singleton class but not in a static class.

How do you Dispose of a singleton object?

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.

What is IDisposable interface in C implement the Dispose method?

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.

How do you use the Dispose method?

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.


1 Answers

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.

like image 135
Drew Noakes Avatar answered Sep 19 '22 01:09

Drew Noakes