I originally come from a C++ background where going out of scope means calling of a destructor and in that destructor is where you clean up everything. The destructor isn't a thing called later at some indeterminate time (like in C#).
New to C# I've been reading a lot about the disposable pattern (because I've made many many mistakes over the past year that resulted in huge amounts of unmanaged resources not being cleaned up resulting in spectacular crashing of programs) and frustratingly it seems like the language made it easier to accidentlly implement incorrectly than it did easy to accidentlly implement correctly.
Take for example:
public void DoSomething() {
using ClassThatImplementsIDisposable obj = new ClassThatImplementsIDisposable();
// do stuff
}
In the above (I think) I've implemented usage of a disposable class correctly. Namely that when I go out of scope the Dispose
method will correctly be called because I added the using
keyword.
But I find while developing that most of the time I remember to add the using
keyword, but occasionally I might forget to add it resulting in unmanaged resource issues, which made me wonder:
Are there ever cases where I'd want to create an object that implements IDisposable AND that variable is going to go out of scope (and by going out of scope I also mean when the reference count goes to zero for objects that are passed around) AND I don't want it to dispose? For example:
public void DoSomething() {
// is there ever a reason to purposefully leave off 'using'
// here on a variable that will go out of scope
ClassThatImplementsIDisposable obj = new ClassThatImplementsIDisposable();
// do stuff
}
if there are cases for the above (which I can't think of any):
- Seem's to me the C# language would've been safer for programmers if they didn't give us the
using
keyword (which would mean all IDisposable objects would be implicitly disposed when reference count goes to zero) and instead maybe they give anotusing
keyword for that weird case where you don't want to dispose (again asking if there are ever cases for this)