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
- 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.
- AddNumbers result = delegate(int x, int y)
- {
- return x + y;
- };
Calling an anonymous method with a reference variable
- 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:
- private static int MultiplyNumbers(AddNumbers addNumbers , int z)
- {
- return addNumbers(10, 20) * z;
- }
Now we need to assign an anonymous method while calling the MultiplyNumbers method:
- int result = MultiplyNumbers(delegate (int x, int y)
- {
- Console.WriteLine("Addition is: " + (x + y));
- return x + y;
- }, 10);
Calling a method:
- Console.WriteLine("Multiplication is: " + result);
Now let's check out the output:
The anonymous method with Lambda expressions:
- AddNumbers result = ( x, y) => x + y;
- 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 @