tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

C#’s overload resolution with enum and object with 0 as value

31 May 2012 .NET, C#

Today I faced surprising behavior once again. Completely off guard.

Let’s have a code:

static void Test(string s, object o)
{
	Console.WriteLine("object");
}
static void Test(string s, TestEnum e)
{
	Console.WriteLine("enum");
}
enum TestEnum
{
	Zero = 0,
	One = 1,
	Two = 2,
}

and call it:

Test("rrr", 0);
Test("rrr", 1);
Test("rrr", 2);
Test("rrr", -1);
Test("rrr", 100);

What do you think you’ll see? Surprisingly, at least for me, it’s:

enum
object
object
object
object

After searching for a while I found Eric Lippert’s post about it. Basically there’s something we can call magic zero and this can be implicitly converted to any enum (even empty one or one without 0 value). That’s the root cause of this behavior. Of course, when C# compiler sees this value in method call, it selects the more specific overload (the one with TestEnum) over the one with object.

Learning new stuff every day…