Sometime ago there was discussion on
StackOverflow about
BinaryWriter implementation. As you may know BinaryWriter and all other
.NET Wrtiers implement
IDisposable. You also might be aware about guidance to always call
Dispose. Boring…
using(var s = File.OpenWrite("1.txt")){
using(var w = new StreamWriter(s)){
...
}
}
The question is… Why? So you have Stream and it
has resources to dispose. Then you have Writer…
And… It does not have resources to dispose. Why to dispose
then? I do not know.
So why they implement IDisposable? I think about
this as a marketing for newbie developers. Most
examples in MSDN looks like:
using (var sw = new StreamWriter("1.txt")) {
...
}
Without IDisposable this code will fail to close
handlers to file. For me this is just leaked design of the
StreamWriter.
At the end of the day, I can formulate my
IDisposable usage.
By default, always call Dispose. But if you
sure what are you doing - do not call!
How to ensure that call to Dispose is not
required? Following is my checklist:
- Think about usage semantics. In most cases, this gives 90% of sure;
- Use .NET Reflector. It can unhide some stuff you may not aware about;
- Read documentation. This also can help to decide;
Anyway, add comment to the code. This will be helpful for maintainers and will reduce questions during reviews.
And remember:
-
Disposeit contract. If one marking code with this contract, for sure he want to say something; -
Things changing. Behaviour of the
Disposecould also change. You will have nothing to say, when your code will not work on .NET 5.0;
BTW
-
DataSetimplementsIDisposable. This is because of usage in .NET Remoting and Design Time support. In additionDataTable,DataViewand evenDataColumnare the same. And no they do not clean data; -
SqlCommandand everything derived fromDbCommand. It does exactly nothing. Why it have? What resources it suppose to own? -
Something not expected at all - ‘SqlCommandBuilder'.
What is expected
Disposedo nothing notable here; -
Each
ComponentimplementsIDisposable. Even if does not own resources. Think about WinFormsBindingSource, ‘ErrorProvider'; -
Ha!,
IEnumerator<T>is also here! This is dark side! -
And at the end
WCF Clients has "broken"
IDisposableimplementation; -
Some stuff could use,
IDisposableas syntax sugar.
Enjoy! Happy coding!
For comments or feedback, write at x.com/chaliy.