Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can’t assign to delegate an anonymous method with less specific parameter type

Tags:

c#

.net

delegates

I’m able to assign a method M to delegate object d with a less specific parameter type, but when I want to assign an anonymous method with same the signature as method M to d, I get an error.

Why is that?

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) { }
like image 402
AspOnMyNet Avatar asked Feb 18 '10 20:02

AspOnMyNet


People also ask

When to use anonymous method in c#?

An anonymous method is a method which doesn't contain any name which is introduced in C# 2.0. It is useful when the user wants to create an inline method and also wants to pass parameter in the anonymous method like other methods.

What is the use of Func delegate in c#?

Func is generally used for those methods which are going to return a value, or in other words, Func delegate is used for value returning methods. It can also contain parameters of the same type or of different types.

Which programming constructs enable the user to specify a small block of code within the delegate declaration?

However, in a situation where creating a new method is unwanted overhead, C# enables you to instantiate a delegate and immediately specify a code block that the delegate will process when it is called. The block can contain either a lambda expression or an anonymous method.

What is anonymous delegates in C#?

Anonymous methods provide a technique to pass a code block as a delegate parameter. Anonymous methods are the methods without a name, just the body. You need not specify the return type in an anonymous method; it is inferred from the return statement inside the method body.


1 Answers

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.

like image 93
JaredPar Avatar answered Sep 23 '22 06:09

JaredPar