Anonymous Method In C#

Introduction

 
Hey there, greetings to you! I hope you are doing well.
 
In accordance with today's topic, let's take a deep dive to understand Anonymous methods in C#.
 
It is called anonymous because it has no name. A method without any name, interesting...
 
Anonymous methods are usually used with delegates. You can learn about delegates in detail here.
 
We know that delegates are used to hold a reference of a method & an anonymous method is nothing but an inline executable block encapsulated within {Curley braces}.
 
Let's understand how to use an anonymous method step by step.
 
We need a delegate to hold a reference of an anonymous method
  1. private delegate int AddNumbers(int x, int y); 
Let's create a reference variable of this delegate and store the anonymous method's reference in it.
  1. AddNumbers result = delegate(int x, int y)  
  2.             {  
  3.                 return x + y;  
  4.             }; 
Calling an anonymous method with a reference variable
  1. Console.WriteLine("Addition is: "+ result(10, 20)); 
We can also pass the anonymous method as a parameter to another method whose parameter type is a delegate.
 
We need a method that accepts delegate:
  1. private static int MultiplyNumbers(AddNumbers addNumbers , int z)  
  2.         {  
  3.             return addNumbers(10, 20) * z;  
  4.         } 
Now we need to assign an anonymous method while calling the MultiplyNumbers method:
  1. int result = MultiplyNumbers(delegate (int x, int y)  
  2.           {  
  3.               Console.WriteLine("Addition is: " + (x + y));  
  4.               return x + y;  
  5.           }, 10); 
Calling a method:
  1. Console.WriteLine("Multiplication is: " + result); 
Now let's check out the output:
 
 
The anonymous method with Lambda expressions:
  1. AddNumbers result = ( x,  y) =>  x + y;  
  2. Console.WriteLine("Addition is: " + result); 
If you want to see how an anonymous method is used in Func, Action or predicate with lambda, feel free to have a look at this article: Func, Action & Predicate in C#.
 
But there are few limitations as well.
  • An anonymous method does not support goto, break, or continue.
  • An anonymous method cannot access ref or out parameters

Conclusion

 
Anonymous methods are easy to implement & easy to understand.
 
This extends our way of using delegates.
 
It is declared inline, hence it saves us a line of code.
 
I hope you understood how to implement anonymous functions in C#.
 
If you have any queries or wants to connect, feel free to reach me @
As always, Happy Coding!


Similar Articles