tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

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

31 May 2012 1 mins .NET, C#

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

Let’s have a code:

static void Test(string s, object o)
static void Test(string s, TestEnum e)
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:


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…

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at