Anonymous Method in C#

Learn via video courses
Topics Covered

Overview

An anonymous method, as the name implies, is one that does not have a name. It enables you to create unnamed delegate methods directly where they are required. Anonymous function C#  allow you to build code blocks that can be utilised as delegate instances in a more compact manner.

This is very useful when you require a short function to be supplied as a parameter to another method but don't want to define a separate named method. This feature becomes especially handy in scenarios where you need to pass succinct pieces of code as parameters to methods, but the task at hand isn't substantial enough to warrant defining a dedicated named function.

Anonymous methods allow you to encapsulate this code within the delegate itself, fostering a more concise and readable codebase.

Introduction to Anonymous Function in C#

Anonymous methods in C# were introduced with version 2.0 to simplify the utilization of delegates, which are essentially pointers to functions that allow passing methods as arguments or storing them in variables. The concept of anonymous methods streamlines delegate usage by enabling the definition of inline delegate implementations without the need for separate method declarations.

Key points to note about anonymous methods include:

  • Anonymous methods are defined using the delegate keyword, followed by a set of parameters and the body of the method enclosed in curly braces {}.
  • The parameters of the anonymous method are enclosed within the method block, defining their scope and enabling them to access variables from their containing scope.
  • This feature allows anonymous methods to capture variables from their containing scope, enhancing their practicality in quickly encapsulating local variables.
  • Anonymous methods do not grant access to unsafe code and do not support jump statements like goto, break, or continue.
  • They can be passed as delegate parameters to methods, leading to cleaner and more readable code. This is particularly advantageous when dealing with methods that expect delegates, such as in LINQ expressions or event handlers.
  • Anonymous methods find their usefulness in scenarios where simple, one-time-use functions need to be passed to methods like those used in LINQ queries or event handling.

Overall, anonymous methods offer a concise way to create and use delegates, improving code readability by embedding small, specialized logic directly inline, while also maintaining access to outer scope variables. Their introduction marked a significant step toward more expressive and streamlined delegate-based programming in C#.

Syntax

The syntax for defining an anonymous method involves specifying the delegate's parameter list and body inline. Here's a general structure:

Examples

Let's take a closer look at some examples to better understand the usage of different anonymous function C#.

Writing an Anonymous Method

Suppose you want to sort a list of integers using the List.Sort method. You can use an anonymous method to define the comparison logic inline:

Example:

Output:

Using the delegate keyword, an anonymous method is created for comparing elements x and y in a list. The comparison is based on x.CompareTo(y). The output "Sorted numbers:" is followed by integers from the list displayed using a foreach loop.

Accessing Variables in the Outer Method

Anonymous methods have the ability to capture variables from their containing scope. This can be extremely useful, as demonstrated in the following example:

Example:

Output:

This C# example showcases anonymous methods accessing outer scope variables. Within ExampleMethod, a local variable externalValue is accessed by an encapsulated anonymous method through an Action delegate. This highlights the ability of anonymous methods to retain access to variables beyond their immediate scope.

Passing an Anonymous Method as a Parameter

Anonymous methods can be passed as arguments to other methods that expect delegates, such as in this example:

Example:

Output

This C# example showcases the application of anonymous methods and delegates. The ProcessNumbers method utilizes a provided delegate filter on an integer list, showing numbers for which the delegate yields true. In the Main method, an inline anonymous method is employed to display even numbers from a list. This underscores

Conclusion

  • Anonymous Function in C# provides concise inline delegate implementations, enhancing code brevity and expressiveness.
  • They improve code flexibility and readability by defining functions within their usage context, simplifying the structure, and eliminating the need for separate named methods.
  • Particularly useful for passing simple, one-time-use functions as parameters, avoiding the need to create dedicated methods.
  • Mastery of anonymous methods leads to more expressive and efficient code, closely aligning with relevant contexts and purposes.
  • Anonymous methods can access outer scope variables even after they've gone out of scope, facilitating seamless interaction with external data.