0

I just started to learn C# and noticed that there are a lot of classes that implement IDisposable interface. The problem, as I see it, is that it's very easy to forget to call Dispose. The compiler/editor does not show any warnings. Is there something that can be done here?

var Thing = new DisposableThing();

class DisposableThing : IDisposable
{
  public void Dispose()
  {
    Console.WriteLine("Disposal is done");
  }
}
manidos
  • 3,244
  • 4
  • 29
  • 65
  • 2
    The problem is the compiler can't know _when_ you'd need to dispose of an object. – AKX May 19 '22 at 15:45
  • 2
    _"it's very easy to forget to call Dispose"_ Not if you make it a habit to _always_ use `using` with disposable objects. – 41686d6564 stands w. Palestine May 19 '22 at 15:46
  • @41686d6564standsw.Palestine 90% of the time i can't use using because the lifetime of my disposable object isn't bound to the local scope. – Ralf May 19 '22 at 15:49
  • @Ralf If your percentage really is 90%, you're probably doing something wrong. In most cases, you don't need to have an instance of the disposable object declared at the class level, and in the other cases where you have to do that, you can often have those objects disposed of when the class containing them is itself disposed of. – 41686d6564 stands w. Palestine May 19 '22 at 15:53

1 Answers1

-1

There is no way to tell if Dispose() was called during compilation time. Method calls happen during runtime.

But you can indeed enforce a correct disposing by implementing IDisposable pattern correctly

https://rules.sonarsource.com/csharp/RSPEC-3881

SirOneOfMany
  • 929
  • 5
  • 15