Skip to content

Latest commit

 

History

History
65 lines (43 loc) · 3.21 KB

delegate-operator.md

File metadata and controls

65 lines (43 loc) · 3.21 KB
title description ms.date helpviewer_keywords
delegate operator - Create an anonymous method that can be converted to a delegate type.
The C# delegate operator that is used to create anonymous methods. These types can be used for `Func<>` and `Action<>` parameters in many .NET APIs.
11/29/2022
delegate [C#]
anonymous method [C#]

delegate operator

The delegate operator creates an anonymous method that can be converted to a delegate type. An anonymous method can be converted to types such as xref:System.Action?displayProperty=nameWithType and xref:System.Func%601?displayProperty=nameWithType types used as arguments to many methods.

[!code-csharp-interactiveanonymous method]

Note

Lambda expressions provide a more concise and expressive way to create an anonymous function. Use the => operator to construct a lambda expression:

[!code-csharp-interactivelambda expression]

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:

[!code-csharp-interactiveno parameter list]

That's the only functionality of anonymous methods that isn't supported by lambda expressions. In all other cases, a lambda expression is a preferred way to write inline code. You can use discards to specify two or more input parameters of an anonymous method that aren't used by the method:

:::code language="csharp" source="snippets/shared/DelegateOperator.cs" id="SnippetDiscards" :::

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

You can use the static modifier at the declaration of an anonymous method:

:::code language="csharp" source="snippets/shared/DelegateOperator.cs" id="SnippetStatic" :::

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.

Beginning with C# 11, the compiler may cache the delegate object created from a method group. Consider the following method:

static void StaticFunction() { }

When you assign the method group to a delegate, the compiler will cache the delegate:

Action a = StaticFunction;

Before C# 11, you'd need to use a lambda expression to reuse a single delegate object:

Action a = () => StaticFunction();

C# language specification

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

See also