Friday, May 16, 2008

An interesting use for using

A college of mine came to see me the other day with a question about some code he had stumbled across. He wasn't exactly sure what it did, or more importantly, if it's something that he should be doing in his code. The code in question was a using block. Now, I'm right up there, telling people that they should have using blocks in their code for any object that implements IDisposable.. The problem was, the object in the using block didn't..













Now, I found this to be very interesting.. myObject was an instance of an object that clearly didn't implement IDisposable. Performing a cast like this would actually result in a null reference. The compiler was happy, the cast was invalid, and it ran without any problems at all.

I took a peek at the IL generated, and was pleasantly surprised to see that there is a check for nulls before the call to dispose.

I'm not sure if there is any benefit from doing this, and I'm sure I wont be recommending this to anybody, I just thought I'd mention it as an interesting tidbit.

Cheers

No comments: