find and solve || findandsolve.com
Please wait.....

Anonymous Method in C#

In C#, An anonymous method is a method that doesn't contain any name which is introduced in C# 2.0. It is useful when the user wants to create an inline method and also wants to pass parameters in the anonymous method like other methods


Syntax:

delegate(ParamList){

    // write Code here..
};

Example 

using System;
public class FindAndSolve {
    public delegate void Test(string test);
    // Main method
    static public void Main() {
        // An anonymous method with one parameter
        Test objTest = delegate(string test)
        {
            Console.WriteLine("I like : {0}",test);
        };
        objTest("Cat");
    }
}

Output

I like : Cat


Some Important Points are given below

  • This method is also known as an inline delegate.
  • Using this method you can create a delegate object without writing separate methods.
  • This method can access variables 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

using System;  

public class FindAndSolve {
    // Create a delegate
    public delegate void Test(string test);
    // Main method
    static public void Main()
    {
        string str = "Dog";
        // Anonymous method with one parameter
        Test objTest = delegate(string test) {
            Console.WriteLine("I like {0}.",test);
            // Accessing variable defined
            // outside the anonymous function
            Console.WriteLine("And I like {0} also.", str);
        };
        objTest("Cat");
    }
}

Output

I like Cat.

And I like Dog also.


  • We can pass this method to another method that accepts delegate as a parameter. As given example:
using System;  

public delegate void Test(string str);
public class FindAndSolve {
    // identity method with two parameters
    public static void identity(Test test, string color) {
        color = " Green" + color;
        test(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 Cat is {0}", color); }," Red");
    }
}

Output

The color of my Cat is Green Red