An anonymous method is an inline method and it does not have a name, i.e, it has body only. We can define it using a delegate.
Let’s try to understand the Anonymous method with the below example. Let’s first create a simple console application.
Syntax:
1 2 3 4 5 |
delegate(parameter_list){ // Code.. }; |
Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// C# program to illustrate how to // create an anonymous function using System; class cce{ public delegate void petanim(string pet); // Main method static public void Main() { // An anonymous method with one parameter petanim p = delegate(string mypet) { Console.WriteLine("My favorite pet is: {0}", mypet); }; p("Dog"); } } |
Output:
1 2 3 |
My favorite pet is: Dog |
Important Points:
- This method is also known as inline delegate.
- Using this method you can create a delegate object without writing separate methods.
- This method can access variable present in the outer method. Such type of variables is known as Outer variables. As shown in the below example fav is the outer variable.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
// C# program to illustrate how an // anonymous function access variable // defined in outer method using System; class cce{ // Create a delegate public delegate void petanim(string pet); // Main method static public void Main() { string fav = "Rabbit"; // Anonymous method with one parameter petanim p = delegate(string mypet) { Console.WriteLine("My favorite pet is {0}.", mypet); // Accessing variable defined // outside the anonymous function Console.WriteLine("And I like {0} also.", fav); }; p("Dog"); } } |
Output:
You can pass this method to another method which accepts delegate as a parameter. As shown in the below example:
1 2 3 4 |
My favorite pet is Dog. And I like Rabbit also. |
You can pass this method to another method which accepts delegate as a parameter. As shown in the below example:
Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
// C# program to illustrate how an // anonymous method passed as a parameter using System; public delegate void Show(string x); class cce{ // identity method with two parameters public static void identity(Show mypet, string color) { color = " Black" + color; mypet(color); } // Main method static public void Main() { // Here anonymous method pass as // a parameter in identity method identity(delegate(string color) { Console.WriteLine("The color"+ " of my dog is {0}", color); }, "White"); } } |
Output:
1 2 3 |
The color of my dog is BlackWhite |