Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline delegate declaration (c#)

Tags:

c#

delegates

I can't get the following to compile:

var x = new Action(delegate void(){}); 

Can anyone point out what I'm doing wrong?

like image 467
maxp Avatar asked Jan 27 '11 11:01

maxp


People also ask

How do you declare a delegate?

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.

How do you call a delegate in C#?

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}"); };

What is Action delegate in C#?

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.


1 Answers

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{}); 
like image 69
Jon Skeet Avatar answered Sep 25 '22 10:09

Jon Skeet