Recently I’ve seen some code written as follows:
public void Dipose()
{
using(_myDisposableField) { }
}
This seems pretty strange to me, I’d prefer to see myDisposableField.Dispose();
What reasons are there for using “using” to dispose your objects over explicitly making the call?
No, none at all. It will just compile into an emptytry/finallyand end up callingDispose.Remove it. You’ll make the code faster, more readable, and perhaps most importantly (as you continue reading below) more expressive in its intent.
Update: they were being slightly clever, equivalent code needs a null check and as per Jon Skeet’s advice, also take a local copy if multi-threading is involved (in the same manner as the standard event invocation pattern to avoid a race between the null check and method call).
From what I can see in the IL of a sample app I’ve written, it looks like you also need to treat
_myDisposableFieldasIDisposabledirectly. This will be important if any type implements theIDisposableinterface explicitly and also provides apublic void Dispose()method at the same time.This code also doesn’t attempt to replicate the
try-finallythat exists when usingusing, but it is sort of assumed that this is deemed unnecessary. As Michael Graczyk points out in the comments, however, the use of thefinallyoffers protection against exceptions, in particular theThreadAbortException(which could occur at any point). That said, the window for this to actually happen in is very small.Although, I’d stake a fiver on the fact they did this not truly understanding what subtle “benefits” it gave them.