开发者

enum method fired when object should be

I a sample C# console application to display a bug I am experiencing:

class Pr开发者_开发技巧ogram
{
    public enum Days { Sat = 1, Sun, Mon, Tue, Wed, Thu, Fri };

    static void Main(string[] args)
    {
        AddWhere("a", DateTime.Now);
        AddWhere("a", 0);
        AddWhere("a", 2);
        AddWhere("a", 3);
        AddWhere("a", "4");
        AddWhere("a", Days.Sun);
        AddWhere("a", Days.Fri);
        AddWhere("a", 1);
        AddWhere("a", (int)Days.Sat);
        Console.Read();
    }

    public static void AddWhere(string columnName, Days cd)
    {
        Console.WriteLine("enum fired");
    }


    public static void AddWhere(string columnName, object Val)
    {
        Console.WriteLine("object fired");
    }
}

the output I get is this:

object fired
enum fired
object fired
object fired
object fired
enum fired
enum fired
object fired
object fired

Why does the enum method fire when 0 is passed in?


The special case of 0 is covered in section 1.10 of the C# language specification.

In order for the default value of an enum type to be easily available, the literal 0 implicitly converts to any enum type

This implicit conversion is causing overload resolution to pick the enum overload over the object one.


JaredPar answered the question. I will add that the work-around is to cast the 0 as the exact type of the desired method overload.

AddWhere("a", (object)0);


Because enums are stored by default as integers and when the compiler tries to resolve the best method overload it decides that AddWhere(string columnName, Days cd) is a better match.


Enum fired because 0 is an int and the enum underlying type is int. 0 is implicitly converted to enum (at compile time) as this conversion is defined by the language.


int a = 123;
long b = a;         // implicit conversion from int to long
int c = (int) b;   // explicit conversion from long to int

Some conversions are defined by the language

Source: msdn.microsoft.com

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜