This is my code:
public class Program
{
public enum SexEnum{
Male,
Female
}
public static void Test(SexEnum s){
Console.WriteLine("enum...");
}
public static void Test(Object s){
Console.WriteLine("object...");
}
public static void Main(string[] args)
{
Test(0);
Test(1);
}
}
But the actual result are:
enum...
object...
Why the enum parameter can NOT accept the int value(>0) in overload method?
This is clearly specified in the language specification, section 6.1.3 Implicit enumeration conversions (emphasis mine):
An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type and to any nullable-type whose underlying type is an enum-type. In the latter case the conversion is evaluated by converting to the underlying enum-type and wrapping the result
So only the literal 0 can be implicitly converted to any enum, not 1, not 2, only 0.
This can be further demonstrated by removing the overload that takes an Object, Test(1) will become unable to compile.
As to why the language is designed this way, you'll have to ask the language designers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With