Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the enum parameter can NOT accept the int value(>0) in overload method

Tags:

c#

enums

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?

like image 775
BD-Joy Avatar asked Oct 20 '25 15:10

BD-Joy


1 Answers

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.

like image 142
Sweeper Avatar answered Oct 23 '25 05:10

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!