I can't get the following to compile:
var x = new Action(delegate void(){});
Can anyone point out what I'm doing wrong?
A delegate can be declared using the delegate keyword followed by a function signature, as shown below. The following declares a delegate named MyDelegate . public delegate void MyDelegate(string msg); Above, we have declared a delegate MyDelegate with a void return type and a string parameter.
In C# 3.0 and later, delegates can also be declared and instantiated by using a lambda expression, as shown in the following example. // Instantiate Del by using a lambda expression. Del del4 = name => { Console. WriteLine($"Notification received for: {name}"); };
C# - Action Delegate Action is a delegate type defined in the System namespace. An Action type delegate is the same as Func delegate except that the Action delegate doesn't return a value. In other words, an Action delegate can be used with a method that has a void return type.
You don't specify a return type when using anonymous methods. This would work:
var x = new Action(delegate(){});
Some alternatives:
Action x = () => {}; // Assuming C# 3 or higher Action x = delegate {}; Action x = delegate() {}; var x = (Action) (delegate{});
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