12

I have one doubt concerning c# method overloading and call resolution.

Let's suppose I have the following C# code:

enum MyEnum { Value1, Value2 }

public void test() {
    method(0); // this calls method(MyEnum)
    method(1); // this calls method(object)
}

public void method(object o) {
}

public void method(MyEnum e) {
}

Note that I know how to make it work but I would like to know why for one value of int (0) it calls one method and for another (1) it calls another. It sounds awkward since both values have the same type (int) but they are "linked" for different methods.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
  • It applies to this statement also MyEnum e = 0; But You will get compiler error (Explicit conversion required) if write this MyEnum e = 1; – RockWorld Mar 25 '10 at 13:07
  • Duplicate of http://stackoverflow.com/questions/1633168/why-does-c-3-allow-the-implicit-conversion-of-literal-zero-0-to-any-enum – Binary Worrier Mar 25 '10 at 13:09

3 Answers3

8

Literal 0 is implicitly convertible to any enum type, which is a closer match than object. Spec.

See, for example, these blog posts.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 1
    0 is implicitly convertible to any enum type while 1 isn't!? – Ahmed Mar 25 '10 at 13:05
  • 4
    @Galilyou: quote from the C# Language Specification (section 1.10): *"In order for the default value of an enum type to be easily available, the literal 0 implicitly converts to any enum type."* – Fredrik Mörk Mar 25 '10 at 13:06
1

I'm pretty sure to call

public void method(MyEnum e) {
}

properly you need to pass in MyEnum.Value1 or MyEnum.Value2. Enum != int type, hence why you have to cast the int to your enum type. So (MyEnum)1 or (MyEnum)0 would work properly.

In your case, 0 was implicitly cast to your enum type.

Bryan Denny
  • 27,363
  • 32
  • 109
  • 125
  • 2
    While your answer is (mostly) correct, that was not what the OP asked about. – Fredrik Mörk Mar 25 '10 at 13:03
  • I still think it is worth mentioning because it is better for readability to code MyEnum.Value1 than to assume that 0 will implicitly cast it to the enum. Then you wouldn't have to worry about falling into the wrong overloaded method – Bryan Denny Mar 25 '10 at 13:07
  • 1
    You're right; that is _definitely_ the best practice. However, it didn't answer the question. – SLaks Mar 25 '10 at 13:09
1

Why does C# allow implicit conversion of literal zero to any enum? is a good reference that has a great answer by JaredPar in it.

Community
  • 1
  • 1
SwDevMan81
  • 48,814
  • 22
  • 151
  • 184