Wednesday, July 29, 2009

A C# Language Quiz

I was writing some code today when I suddenly realized that I didn't how a certain very fundamental part of the C# language would behave.

Here's an example:
using System;

namespace TestNullCastToObject
{
class Program
{
static void Main( string[] args )
{
Test t = null;
object o = t;
if ( o is Test )
Console.WriteLine( "a Null Test is a Test" );
else
Console.WriteLine( "a Null Test is _NOT_ a Test" );

Console.ReadLine();
}
}

class Test
{
public int Id { get; set; }
}
}


If you compile and run that sample what do you think the output will be?

No really, think about it.

Ok, I'll tell you what I thought the output would be. I thought the output would be "a Null Test is a Test".

Ok, now I'm going to tell you what the output is.

"a Null Test is _NOT_ a Test"


Does that surprise you as much as it did me? I think I'm actually happy that it behaves this way, but I'm still surprised.