Why the following two code samples produce different output?
Case 1
enum EnumType
{
First,
Second,
Third
}
class ClassB
{
public string Func(int index)
{
return "Func(int)";
}
public string Func(EnumType type)
{
return "Func(EnumType)";
}
}
class Program
{
static void Main(string[] args)
{
ClassB b = new ClassB();
Console.WriteLine(b.Func(0));
Console.WriteLine(b.Func(EnumType.First));
Console.ReadLine();
}
}
Output:
Func(int)
Func(EnumType)
Case 2
enum EnumType
{
First,
Second,
Third
}
class ClassA
{
public string Func(int index)
{
return "Func(int)";
}
}
class ClassB : ClassA
{
public string Func(EnumType enumType)
{
return "Func(EnumType)";
}
}
class Program
{
static void Main(string[] args)
{
ClassB b = new ClassB();
Console.WriteLine(b.Func(0));
Console.WriteLine(b.Func(EnumType.First));
Console.ReadLine();
}
}
Output:
Func(EnumType)
Func(EnumType)
I am puzzled. Does it mean that Func(EnumType) hides Func(int) declared in the base? If this is the case then why literal 0 is implicitly casted to EnumType in the second case without a warning?
EDIT:
There is even more interesting behavior when I try
Console.WriteLine(b.Func(0));
Console.WriteLine(b.Func(1));
Console.WriteLine(b.Func(EnumType.First));
What is your guess the output should look like?
here it is:
Func(EnumType)
Func(int)
Func(EnumType)
Any ideas why 0 and 1 are treated differently?
EDIT 2:
It turns out that literal 0 indeed has special meaning in C#.
Here and here I found an excellent description of this behavior (see the accepted answers).