22 Mar 2011

Recently, I discovered something like this my current codebase:

var g = Guid.NewGuid();

if (g == null) throw new Exception("Exception");

Of course, there are other statements in between, this is just an over simplifications. The idea, however, is to compare a value type with null, which makes no sense if you know .NET a bit, but can be found all over the world I am sure.

Without checking, I was sure that this would result in boxing the value type, followed by a comparison of the reference of the box with null, which will always return false.

Well, it turns out that I was wrong. The compiler is smart enough and ignores the statement in this case, as it is useless.

Now, what if there is an else statement in there?

if (g == null) throw new Exception("Exception");
else Console.WriteLine("boxed?");

In this case, the compiler only emits that is in the else statement. It is once more smart enough.

Let’s push it a little bit. What happens if we do this:

var b = (g == null);

if (b) Console.WriteLine("boxed?");

In this case, the compiler will emit all the instructions, although it’s obvious that Console.WriteLine will never be executed. But still, no boxing.

Once more, C#’s compiler is very smart about all this. There is no boxing happening in the three cases.



blog comments powered by Disqus