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?
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);
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