I recently came across some interesting code in Juval Löwy’s Programming WCF Services and wanted to share. It’s simply something I had never run across before:
The first thing to notice is that the proxy object is instantiated outside of the using block. I don’t think I’ve ever actually tried this, but it is perfectly permissible (if not recommended). I used a dissembler to look at the IL this generates, and it is pretty much the same as instantiating the proxy object inside of the using brackets. The main difference is that in this case, the scope of the proxy object extends beyond the using block.
Within the using brackets, this code casts the proxy object to the IDisposable interface so the Dispose method will be available. Since a Using Block is basically syntactic sugar for a try-catch-finally structure that calls an object’s Dispose method in the finally block, the equivalent try-catch-finally block would look like this:
However, Juval’s using statement does one additional thing. It also checks to see if the proxy object even implements the IDisposable interface. If it does, then the Dispose method is called on it. If it does not, then nothing happens in the finally block. The equivalent full blown code, then, would actually look something like this:
… and we’ve condensed it to this …
It’s probably not something that will come up too often, but if you have a situation in which you do not know whether an object implements IDisposable or not, but still want to implement a using block for readability and good coding practice, this is how you would go about doing it.
Besides Juval’s proxy example, I can imagine it coming in handy when dealing with collections in which you don’t necessarily know whether all of the members of the collection implement IDisposable, for instance:
It also just looks really cool. h/t to Bill Ryan for pointing this out to me.