Sunday, September 22, 2013

.net under the covers — using/Using/use

Something I had occasion to look at the other day was exactly how the auto-disposal mechanism actually works for the out of the box .net languages: and there are some interesting quirks to be found. Take the equivalent sample code fragments

and for completeness, C++/CLI stack based disposal

All languages and configurations render this as a try {} finally { Dispose() } construction (apart from stack-based C++/CLI semantics, which generates a try {} catch { Dispose(); throw;} Dispose()), but there are devils in the details. In release mode, C# and VB compile to the same IL -- just dispose if the used value is not null


whereas F# compiles to

which is unexpected, as the compiler enforces the subject of a use initialisation to be an IDisposable anyway -- but, importantly, it does not test for null on the original reference.


In debug mode, all three languages differ, C# flips the test around

VB does something a bit more like F#

and F# just adds one of its usual bursts of gratuitous branching in the middle

The C++/CLI code can rely on the stack-based object not being null, so eschews any checks

No comments :