Search code examples
c#.netdelegatesmethod-group

When is it valid to say a method group conversion has taken place?


So i'm not really convinced when its safe to say that a method group conversion occured. We have this multicast delegate from a previous post:

public partial class MainPage : PhoneApplicationPage
{
public delegate void MyDelegate(int a, int b);
// Constructor
public MainPage()
{
    InitializeComponent();

    MyDelegate myDel = new MyDelegate(AddNumbers);
    myDel += new MyDelegate(MultiplyNumbers);
    myDel(10, 20);
}

public void AddNumbers(int x, int y)
{
    int sum = x + y;
    MessageBox.Show(sum.ToString());
}

public void MultiplyNumbers(int x, int y)
{
    int mul = x * y;
    MessageBox.Show(mul.ToString());
}
}

I say that a method group conversion only occurs when we have assigned a method thats overloaded, and at least one overload matches the delegate. In this case there is no method group conversion.

a fellow programmer says that if you don't think MyDelegate myDel = AddNumbers; (with names referring to the question) is a method group conversion, then what would it be then?

The C# Language Specification: An implicit conversion (§6.1) exists from a method group (§7.1) to a compatible delegate type. Given a delegate type D and an expression E that is classified as a method group, an implicit conversion exists from E to D if [...]

So wich point of view is correct?


Solution

  • I say that a method group conversion only occurs when we have assigned a method thats overloaded

    Nope, there's no requirement of overloading (by multiple methods) for method group conversions.

    Any time you've got just a method name, or a method name qualified with a target (e.g. MultiplyNumbers or foo.MultiplyNumbers), that's a method group. If you're converting that to a delegate instance, that's a method group conversion.

    EDIT: The section of the spec which is causing problems is this, in 7.1:

    A method group, which is a set of overloaded methods resulting from a member lookup (7.4).

    That "set of overloaded methods" can be a set of size 1 - it's still a method group.

    This is backed up by 7.6.5.1 (Method Invocations) - emphasis mine:

    For a method invocation, the primary-expression of the invocation-expression must be a method group. The method group identifies the one method to invoke or the set of overloaded methods from which to choose a specific method to invoke.

    That makes it clear that a method group with one element is a meaningful concept.