tags:

views:

153

answers:

2

I’m able to assign to delegate object d a method M with less specific parameter type, but if I want to assign to d an anonymous method with same signature as method M, then I get an error. Any idea why that is?

    class derivedEventArgs : EventArgs { }

    delegate void newDelegate(object o, derivedEventArgs e); 

    static void Main(string[] args)
    {
        newDelegate d = M; // ok
                    d = (object o, EventArgs e) => { }; // error
    }

    public static void M(object o, EventArgs e) { }

thanx

+13  A: 

This is covered in section 6.5 of the C# language specification. If you explicitly type the parameters of an anonymous function, they must match in both type and modifiers in order to be compatible signatures.

Specifically, a delegate type D is compatible with an anonymous function F provided

...

If F has an explicitly typed parameter list, each parameter in D has the same type and modifiers as the corresponding parameter in F.

JaredPar
+1 very quick answer.
Stan R.
+8  A: 

Jared is of course correct that this is by design.

The reason for that design is that in the contravariant method conversion case, you might have a method that you didn't write, and be assigning it to a delegate variable that you didn't write either. You don't control the types. So we go a bit easy on you and let the parameters match contravariantly and the return types match covariantly.

In the lambda-to-delegate conversion, you do control the thing being assigned. There is nothing stopping you from making it an exact match in the parameter types and therefore we require you to. No fudging allowed here.

Eric Lippert
Great answers.Thank you both for helping me out
AspOnMyNet