c-sharp
  1. c-sharp-anonymous-function

C# Anonymous Function

In C#, an anonymous function is a function that doesn't have a name and can be assigned to a delegate or used as a parameter in a method call. Anonymous functions are useful for creating simple code blocks that can be reused in your code. In this tutorial, we'll discuss how to use anonymous functions in C#.

Syntax

The syntax for defining an anonymous function in C# is as follows:

delegate(parameters) {
   // code
}

The "delegate" keyword is followed by the parameter list in parentheses, and then the code block in curly braces.

Example

Let's say we have an array of integers and we want to filter out all even numbers. Here's how we can do it using an anonymous function:

int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] evenNumbers = Array.FindAll(numbers, delegate(int num) {
   return num % 2 == 0;
});

In the code above, we defined an array of integers and used an anonymous function to filter out all even numbers and assign them to a new array.

Output

When we run the example code above, the "evenNumbers" array will contain the values {2, 4, 6, 8}.

Explanation

In the example above, we used an anonymous function to filter out all even numbers from an array of integers. We passed the array and a delegate to the Array.FindAll method and used an anonymous function to filter the values. The anonymous function takes an integer parameter and returns a boolean value indicating whether the integer is even or not.

Use

Anonymous functions are useful for creating simple code blocks that can be reused in your code. They are often used when you need to define a code block that doesn't need to be reused elsewhere in the code.

Important Points

  • Anonymous functions support all C# language constructs, including loops, conditionals, and switch statements.
  • Anonymous functions can capture variables from the enclosing scope, making it possible to define closures.
  • Anonymous functions can be used interchangeably with lambdas in many cases.

Summary

In this tutorial, we discussed how to use anonymous functions in C#. We covered the syntax, example, output, explanation, use, and important points of anonymous functions in C#. With this knowledge, you can now use anonymous functions in your C# code to create simple code blocks that can be reused throughout your application.

Published on: