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) { }
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With