views:

101

answers:

4

Hello all,

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.

Ps.: This is my first question here, i'm sorry if I made something wrong. =P

+6  A: 

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

See, for example, these blog posts.

SLaks
0 is implicitly convertible to any enum type while 1 isn't!?
Galilyou
@Galilyou: Correct.
SLaks
@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
+1  A: 

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
While your answer is (mostly) correct, that was not what the OP asked about.
Fredrik Mörk
Read the question.
SLaks
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
@Bryan: You're right; that is _definitely_ the best practice. However, it didn't answer the question.
SLaks
+1  A: 

This has already been answered here

Barry
+1  A: 

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.

SwDevMan81