delegate operator (C# reference)

The delegate operator creates an anonymous method that can be converted to a delegate type:

Func<int, int, int> sum = delegate (int a, int b) { return a + b; };
Console.WriteLine(sum(3, 4));  // output: 7


Beginning with C# 3, lambda expressions provide a more concise and expressive way to create an anonymous function. Use the => operator to construct a lambda expression:

Func<int, int, int> sum = (a, b) => a + b;
Console.WriteLine(sum(3, 4));  // output: 7

For more information about features of lambda expressions, for example, capturing outer variables, see Lambda expressions.

When you use the delegate operator, you might omit the parameter list. If you do that, the created anonymous method can be converted to a delegate type with any list of parameters, as the following example shows:

Action greet = delegate { Console.WriteLine("Hello!"); };

Action<int, double> introduce = delegate { Console.WriteLine("This is world!"); };
introduce(42, 2.7);

// Output:
// Hello!
// This is world!

That's the only functionality of anonymous methods that is not supported by lambda expressions. In all other cases, a lambda expression is a preferred way to write inline code.

Beginning with C# 9.0, you can use discards to specify two or more input parameters of an anonymous method that aren't used by the method:

Func<int, int, int> constant = delegate (int _, int _) { return 42; };
Console.WriteLine(constant(3, 4));  // output: 42

For backwards compatibility, if only a single parameter is named _, _ is treated as the name of that parameter within an anonymous method.

Also beginning with C# 9.0, you can use the static modifier at the declaration of an anonymous method:

Func<int, int, int> sum = static delegate (int a, int b) { return a + b; };
Console.WriteLine(sum(10, 4));  // output: 14

A static anonymous method can't capture local variables or instance state from enclosing scopes.

You also use the delegate keyword to declare a delegate type.

C# language specification

For more information, see the Anonymous function expressions section of the C# language specification.

See also