none
Unexpect method calls with extentions overloads RRS feed

  • Question

  • Hi,

    I have the following code 

    void Main()
    {
        var a = new A();
    	a.Foo(1);
    	a.Foo(0);
    }
    
    public enum MyEnum
    {
      None = 0,
      One = 1
    }
    
    
    public class A
    {
      public void Foo(MyEnum en)
      {
        Console.WriteLine("MyEnum");
      }
    }
    
    public static class Extention
    {
       public static void Foo(this A o, int x)
       {
          Console.WriteLine("int");
       }
    }
    
    I expect "int int" as result, but I got "int MyEnum". Is it compiler bug or some design feature?

    Tuesday, October 28, 2014 12:22 PM

Answers

  • Seems to be a feature but not the obvious one:

    An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type and to any nullable-type whose underlying type is an enum-type. In the latter case the conversion is evaluated by converting to the underlying enum-type and wrapping the result.

    Because of that compiler decides the instance method is a better match than extension method.

    • Proposed as answer by Blackwood Tuesday, October 28, 2014 3:48 PM
    • Marked as answer by Sergey Dramarecky Friday, October 31, 2014 8:55 PM
    Tuesday, October 28, 2014 3:35 PM

All replies

  • Seems to be a feature but not the obvious one:

    An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type and to any nullable-type whose underlying type is an enum-type. In the latter case the conversion is evaluated by converting to the underlying enum-type and wrapping the result.

    Because of that compiler decides the instance method is a better match than extension method.

    • Proposed as answer by Blackwood Tuesday, October 28, 2014 3:48 PM
    • Marked as answer by Sergey Dramarecky Friday, October 31, 2014 8:55 PM
    Tuesday, October 28, 2014 3:35 PM
  • Thanks.
    Tuesday, October 28, 2014 3:42 PM