Search code examples
c#garbage-collectionusingidisposable

Set all properties to null is a valid way to dispose an object?


Using statement requires the object type to directly implement IDisposable.

Looking for the easiest to do so, came up with this snippet.

public class Foo : IDisposable
{
    public string? exampleProperty { get; set; }

    public virtual void Dispose()
    {
        foreach(var property in GetType().GetProperties())
        {
            property.SetValue(this,null);
        }
    }
}

It compiles and runs, I can even use it inside using block normally. But, is that a proper manner to do it?

For investigative purposes:

using (var x = new Foo() { exampleProperty = "Xpto"})
{
    //do something
}

in this case, Foo will became an Api request response


Solution

  • The IDisposable-interface is ment to dispose everything that your GarbageCollector cannot handle - namely unmanaged objects.

    Provides a mechanism for releasing unmanaged resources.

    In your code you have only managed types - i.e. strings - which the GC can handle very well.

    A using-statement is just a wrapper around a try-finally-block, which will call Dispose in the finally-statement.

    IDisposable a;
    try { a = ... }
    finally { a.Dispose(); }
    

    As there's nothing to be disposed in your code, implementing the interface and therefor also using a using is completely pointless. Just let the collector do its job.