Anonymous Method in C#

An anonymous method is a method which 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 parameter in the anonymous method like other methods. An Anonymous method is defined using the delegate keyword and the user can assign this method to a variable of the delegate type.

Syntax:

delegate(parameter_list){
    // Code..
};

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to illustrate how to 
// create an anonymous function
using System;
  
class GFG {
  
    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");
    }
}

chevron_right


Output:

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:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // C# program to illustrate how an 
    // anonymous function access variable
    // defined in outer method
    using System;
      
    class GFG {
      
        // 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");
        }
    }

    chevron_right

    
    

    Output:

    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 :

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // C# program to illustrate how an 
    // anonymous method passed as a parameter
    using System;
      
    public delegate void Show(string x);
      
    class GFG {
      
        // 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");
        }
    }

    chevron_right

    
    

    Output:

    The color of my dog is  BlackWhite
    
  • In anonymous methods, you are allowed to remove parameter-list, which means you can convert an anonymous method into a delegate.
  • The anonymous-method-block means the scope of the parameters in the anonymous method.
  • An anonymous method does not contain jump statements like goto, break, or continue.
  • An anonymous method does not access unsafe code.
  • An anonymous method does not access in, ref, and out parameter of the outer scope.
  • You can not use an anonymous method to the left side of the is operator.
  • You can also use an anonymous method as an event handler.

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // C# program to illustrate how an 
    // anonymous method use as a 
    // event handler
    MyButton.Click += delegate(Object obj, EventArgs ev)
    {
        System.Windows.Forms.MessageBox.Show("Complete without error...!!");
    }

    chevron_right

    
    



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.