In c#, anonymous methods are the methods without a name. Generally, the anonymous methods can define by using the delegate keyword and can be assigned to the variable of the delegate type.
Following is the sample way of creating anonymous methods in c# using the delegate keyword.
If you observe the above code, we created an anonymous method, passed it as a delegate parameter, and assigned it to a variable of the delegate type.
In c#, anonymous methods are useful to reduce the coding overhead in instantiating delegates because we don’t have to create a separate method.
If we define any parameters in anonymous methods, those can access only within the anonymous method block, but the anonymous methods can access the variables we define in outer functions.
Following is the example of creating anonymous methods in c# using the delegate keyword.
If you observe the above code, we created an anonymous method, passing it as a delegate parameter, and we are able to access outside variables within the anonymous method.
When we execute the above code, we will get the below result.
In c#, we can pass an anonymous method as a parameter to the method that accepts delegate as a parameter.
Following is the example of sending an anonymous method as a parameter to another method in c#.
If you observe the above code, we created an anonymous method and passed it as a parameter to the other method (GetInfo).
When we execute the above code, we will get the below result.
This is how we can send an anonymous method as a parameter to another method in c# based on our requirements.
Following are some of the limitations of anonymous methods in c#.
The anonymous methods are introduced in C# 2.0 to create methods without a name, but in C# 3.0 and later versions, the lambda expressions have been introduced to achieve better functionality than anonymous methods by writing inline code. To learn more about lambda expressions, check LINQ Lambda Expressions.
Following are the important points that we need to remember about the anonymous methods in c#.