Search code examples
c#delegatesoverload-resolution

Why cannot C# resolve the correct overload in this case?


I've come across a strange situation which is non-ambiguous, yet the overload resolver doesn't think so. Consider:

public static class Program
{
    delegate int IntDel();
    delegate string StringDel();

    delegate void ParamIntDel(int x);
    delegate void ParamStringDel(string x);

    static void Test(IntDel fun) { }
    static void Test(StringDel fun) { }
    static void ParamTest(ParamIntDel fun) { }
    static void ParamTest(ParamStringDel fun) { }

    static int X() { return 42; }
    static void PX(int x) { }

    public static void Main(string[] args)
    {
        ParamTest(PX); // OK
        Test(X); // Ambiguos call!
    }
}

How come the call to ParamTest overloads is resolved correctly, but Test overload is ambiguous?


Solution

  • Perhaps because https://msdn.microsoft.com/en-us/library/aa691131%28v=vs.71%29.aspx

    The signature of a method specifically does not include the return type, nor does it include the params modifier that may be specified for the right-most parameter.

    And the only difference between IntDel and StringDel is in the return value.

    More specifically: https://msdn.microsoft.com/en-us/library/ms173171.aspx

    In the context of method overloading, the signature of a method does not include the return value. But in the context of delegates, the signature does include the return value. In other words, a method must have the same return type as the delegate.