-1

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

  • 4
    That's not what IDisposable is for. A type should implement IDisposable if instances of it either own and manage unmanaged resources or own other IDisposable instances. The purpose of the Dispose method therefore is to clean up and release unmanaged resources and/or dispose other IDisposable instances held by this object instance... –  Oct 11 '22 at 16:00
  • 1
    having said this your in your code there's no need to implement it and thus no need to use a `using`. Only because you say you want it that way doesn't make it work that way. – MakePeaceGreatAgain Oct 11 '22 at 16:01
  • what would be the correct way to destroy an object after using it for a unique purpose? – James Jonatah Oct 11 '22 at 16:02
  • 1
    As @MySkullCaveIsADarkPlace mentioned, that is not what IDisposable is for. Individual properties on objects do not need to be disposed, and 90% of classes do not need to be disposed after using. Items that generally require disposing includes database connection/context, file stream, or other resource that may hold onto resources. https://stackoverflow.com/questions/538060/proper-use-of-the-idisposable-interface – Anthony G. Oct 11 '22 at 16:03
  • 4
    there's no need to destroy it, let the GC do it when its references are out of scope. That's the entire point of GC. – MakePeaceGreatAgain Oct 11 '22 at 16:04

1 Answers1

1

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.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111