C#/.NET Little Pitfalls: Implicit Zero To Enum Conversion

added by BlackRabbitCoder
1/27/2012 2:19:18 PM

2 Kicks, 325 Views

Many times, we create overloaded methods or constructors to allow them to accept different kinds of data. Further, there are times that we may accept object when any value will do. This works well (aside from boxing/unboxing concerns for value types), but if you have an overload that accepts object and one that takes an enum, and you pass a constant expression of 0, where does it go?


1/26/2012 7:30:31 PM
new post

1/27/2012 2:20:11 PM
Now, the reason lies in the implementation of Equals correct? Since the default first enumerator for the enum is zero? Does the same problem happen if you pass in the literal value of 1, corresponding to another item in your enum?

1/29/2012 10:55:46 PM
Actually, no. It is purely an implicit conversion in the language itself from a const zero expression to an enum. 1, etc, won't make the conversion implicitly. Zero to enum is a special case.