What is an anonymous function in C#?

In C#, an anonymous function is a function that is defined without a name and is typically used for concise and inline function definitions. It allows you to create a function “on the fly” without the need for explicitly naming and defining a separate method.

Anonymous functions can be created using several syntax forms in C#:

  1. Lambda Expressions:
    • Lambda expressions are a concise syntax for creating anonymous functions.
    • They are denoted by the => (lambda) operator, separating the parameter list from the expression or statement body.
    • Lambda expressions are commonly used with delegates or functional interfaces to define inline functions.
Func<int, int> square = x => x * x;
  1. Anonymous Methods:
  • Anonymous methods provide a more traditional syntax for creating anonymous functions.
  • They are defined using the delegate keyword and a parameter list, followed by the method body enclosed in curly braces {}.
  • Anonymous methods are often used with delegates for event handling or asynchronous programming.


Action<int> printNumber = delegate(int number)
  1. Func and Action delegates:
  • Func and Action delegates provide a way to create and use anonymous functions without explicitly declaring a delegate type.
  • Func delegates represent functions with a return value, while Action delegates represent functions without a return value.
  • You can use them to define anonymous functions directly as arguments to methods or for functional programming scenarios.


var result = PerformOperation(x => x * x);

Anonymous functions are commonly used for simple and short-lived functions, such as in LINQ queries, event handling, or functional programming scenarios. They provide a way to define and use functions inline without the need for separate method definitions, making the code more concise and expressive.

It’s important to note that anonymous functions capture variables from their surrounding context, known as variable capture or closure. This allows them to access variables from the enclosing scope, even after the enclosing code has finished execution. This behavior is especially useful when working with asynchronous programming or LINQ queries.

Overall, anonymous functions in C# provide a convenient way to define small and inline functions without the need for named method declarations. They enhance code readability and maintainability by reducing the amount of boilerplate code required for simple function definitions.

error: Content is protected !!