Example code:
internal class Program
{
static void Main(string[] args)
{
Foo foo = new Foo();
}
}
public class Foo : IDisposable
{
public void Dispose()
{
// Not invoked.
Console.WriteLine("Foo disposed");
}
}
Here the Foo type is IDisposable, but the 'foo' variable is not wrapped in a 'using' statement; either the traditional syntax with a 'using' block/scope, or the newer syntax that calls Dispose() when the variable goes out of scope, like so:
using Foo foo = new Foo();
Given that this could be a source of resource leaks, why is there no compiler warning or analyzer rule for this scenario?
This seems like an obvious thing to check, and therefore I suspect this omission is for a good reason.
EDIT: Removed the bad example that ignored the leaveOpen
constructor argument of StreamWriter
. Upon rethinking it, I also realized the data would remain unflushed unless Dispose
was called so disposing was the right call there.
I am quite sure it is because you do not always want to Dispose
objects. For example Task
objects are IDisposable
, but you normally never dispose of them explicitly. There are probably more types like this, i.e. types that only rarely allocate unmanaged resources and which should only be disposed if their finalizers are slowing down your application.
Furthermore, if your class has unmanaged resources that need to be disposed no matter what, then it should be implementing the Dispose Pattern by using finalizers, not relying on someone not forgetting to write using
.
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