Monday, July 6, 2020

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 :



// 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");
    }
}
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.

No comments:

Post a Comment