Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enum method fired when object should be

Tags:

c#-3.0

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

class Program
{
    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?

like image 363
Chris Avatar asked May 26 '26 11:05

Chris


2 Answers

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.

like image 188
JaredPar Avatar answered May 28 '26 01:05

JaredPar


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);
like image 34
Jeffrey L Whitledge Avatar answered May 28 '26 01:05

Jeffrey L Whitledge



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!