Anonymous Method in C#

Anonymous Method in C# with examples

In this article, I am going to discuss the Anonymous Method in C# with examples. Please read our previous article where we discussed one real-time example of the delegate. As part of this article, we are going to discuss the following concepts of Anonymous methods in detail.

  1. What is Anonymous Method in C#?
  2. Why do we need Anonymous Methods in C#?
  3. Examples of Anonymous Method.
  4. What are the Advantages of Using Anonymous Methods in C#?
  5. Examples of Anonymous methods accessing variables defined in an outer function.
  6. What are the Limitations of Anonymous Methods in C#?
  7. Anonymous Methods Real-time Examples in C#
What is Anonymous Method in C#?

As the name suggests, an anonymous method in C# is a method without having a name. The Anonymous methods in C# can be defined using the keyword delegate and can be assigned to a variable of the delegate type.

Why do we need Anonymous Methods in C#?

In our Delegates in C# article, we discussed how to bind a delegate with a method. To bind a delegate with a method, first, we need to create an instance of a delegate and when we create the instance of a delegate, we need to pass the method name as a parameter to the delegate constructor, and it is the function the delegate will point to.

Below is the example to understand Delegate in C#.
namespace DelegateDemo
{
    public class AnonymousMethods
    {
        public delegate string GreetingsDelegate(string name);
        public static string Greetings(string name)
        {
            return "Hello @" + name + " Welcome to Dotnet Tutorials";
        }

        static void Main(string[] args)
        {
            GreetingsDelegate gd = new GreetingsDelegate(AnonymousMethods.Greetings);
            string GreetingsMessage = gd.Invoke("Pranaya");
            Console.WriteLine(GreetingsMessage);
            Console.ReadKey();
        }
    }
}
OUTPUT:

Anonymous Method in C#

In the above example,

  1. We create one delegate (GreetingsDelegate)
  2. Then we instantiate the delegate, while we are instantiating the delegate, we are passing the Method name as a parameter to the constructor of the delegate
  3. Finally, we invoke the delegate

As of now, this is the approach we are following to bind a method to a delegate and execute. An anonymous method is also related to a delegate. Without binding a named block (function) to a delegate, we can also bind a code block to a delegate means an unnamed code blocked to a delegate which is nothing but an anonymous method in C#.

Let’s see an example for a better understanding of the Anonymous Methods in C#.
namespace DelegateDemo
{
    public class AnonymousMethods
    {
        public delegate string GreetingsDelegate(string name);
        
        static void Main(string[] args)
        {
            GreetingsDelegate gd = delegate(string name) 
            {
                return "Hello @" + name + " Welcome to Dotnet Tutorials";
            };
            string GreetingsMessage = gd.Invoke("Pranaya");
            Console.WriteLine(GreetingsMessage);
            Console.ReadKey();
        }
    }
}
OUTPUT:

Anonymous Method in C#

In the above example, the following code is an example of an Anonymous method.

Anonymous Method in C#

The above code is without a name and it contains only the body and the method is defined using the delegate keyword. We don’t require writing any access modifiers like public, private, and protected, etc. We also don’t require writing any return type like a void, int, double, etc.

What are the Advantages of Using Anonymous Methods in C#?

Lesser typing word.  Generally, anonymous methods are suggested when the code volume is very less.

Examples of Anonymous methods accessing variables defined in an outer function. 

Let’s see an example for a better understanding.

namespace DelegateDemo
{
    public class AnonymousMethods
    {
        public delegate string GreetingsDelegate(string name);
        
        static void Main(string[] args)
        {
            string Message = "Welcome to Dotnet Tutorials";

            GreetingsDelegate gd = delegate(string name) 
            {
                return "Hello @" + name + " " + Message;
            };

            string GreetingsMessage = gd.Invoke("Pranaya");
            Console.WriteLine(GreetingsMessage);
            Console.ReadKey();
        }
    }
}
OUTPUT:

Anonymous Method in C#

What are the Limitations of Anonymous Methods in C#?
  1. An anonymous method in C# cannot contain any jump statement like goto, break or continue.
  2. It cannot access the ref or out parameter of an outer method.
  3. The Anonymous methods cannot have or access the unsafe code.
Points to Remember while working with the Anonymous Methods in C#:
  1. The anonymous methods can be defined using the delegate keyword
  2. An anonymous method must be assigned to a delegate type.
  3. This method can access outer variables or functions.
  4. An anonymous method can be passed as a parameter.
  5. This method can be used as event handlers.
Anonymous Method Real-Time Example in C#

As the name suggests, an anonymous method is a method without having a name. Anonymous methods in C# can be defined using the keyword delegate and can be assigned to a variable of the delegate type. In simple terms, an anonymous method is a method without a name.  

Let’s understand how a method can exist without a name in C# with one example.

Step1:

Create a class Employee and copy and paste the below code

Anonymous Method Real-Time Example in C#

Step2:

In our Generic Delegates in C# article, we already discussed that Predicate is a generic delegate that accepts a single input parameter of any type and returns a Boolean value which is mandatory and fixed. Following is the signature of Predicate Generic Delegate.

Anonymous Method Real-Time Example in C#

As shown in the image above, the Predicate Generic delegate takes an input parameter of type T (in T) and returns a Boolean value. Now, we need to create a method whose signature must match with the signature of Predicate<Employee> delegate

Anonymous Method Real-Time Example in C#

As shown in the above image, the GetEmployee method takes one input parameter of type Employee and returns a Boolean value. So the above method signature matches the signature of the Predicate generic delegate.

The method logic is very simple. It checks the ID value of the employee which is passed as a parameter to this function, if the ID value is 103, then it returns true else it returns false.

Step3:

In this step, we are going to create an instance of the Predicate Generic Delegate. While we are creating the instance, we need to pass the GetEmployee method as a parameter to the constructor of Predicate as shown in the image below.

Anonymous Method Real-Time Example in C#

Step4:

Now we need to create a collection of Type Employee to hold a list of Employees as shown in the below image.

Anonymous Method Real-Time Example in C#

Step5:

In this step, we need to pass the delegate instance to the Find method of List collection class as shown in the image below

Anonymous Method Real-Time Example in C#

We are done. The complete code is shown below
namespace AnonymousMethodRealTimeExample
{
    public class Program
    {
        public static void Main()
        {
            //Step4
            //Create a collection of List of Employees
            List<Employee> listEmployees = new List<Employee>()
            {
                new Employee{ ID = 101, Name = "Pranaya", Gender = "Male", Salary = 100000},
                new Employee{ ID = 102, Name = "Priyanka", Gender = "Female", Salary = 200000},
                new Employee{ ID = 103, Name = "Anurag", Gender = "Male", Salary = 300000},
                new Employee{ ID = 104, Name = "Preety", Gender = "Female", Salary = 400000},
                new Employee{ ID = 104, Name = "Sambit", Gender = "Male", Salary = 500000},
            };

            // Step 3: 
            // Create an instance of Predicate<Employee> delegate and pass
            // the method name as an argument to the delegate constructor          
            Predicate<Employee> employeePredicate = new Predicate<Employee>(GetEmployee);

            // Step 5: 
            // Now pass the delegate instance as the
            // argument to the Find() method of List collection
            Employee employee =
                listEmployees.Find(x => employeePredicate(x));
            Console.WriteLine(@"ID : {0}, Name : {1}, Gender : {2}, Salary : {3}",
                employee.ID, employee.Name, employee.Gender, employee.Salary);

            Console.ReadKey();    
        }

        // Step 2: 
        // Create a method whose signature matches with the
        // signature of Predicate<Employee> generic delegate
        private static bool GetEmployee(Employee Emp)
        {
            return Emp.ID == 103;
        } 
    }

    // Step1
    // Create a class called Employee with
    // ID, Name, Gender and Salary Properties
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public double Salary { get; set; }
    }
}
OUTPUT:

Anonymous Method Real-Time Example in C#

Use the anonymous method.

As of now what we did?

  1. We create a method whose signature matches with the Predicate Generic Delegate
  2. Then we create an instance of the Predicate Generic Delegate
  3. Then we pass that Predicate Instance as an argument to the Find method of the List collection class

Using an anonymous method, we can safely avoid the above three steps. We can pass an anonymous method as an argument to the Find() method as shown in the image below.

Anonymous Method Real-Time Example in C#

The complete code is given below.
namespace AnonymousMethodRealTimeExample
{
    public class Program
    {
        public static void Main()
        {
            //Step2
            //Create a collection of List of Employees
            List<Employee> listEmployees = new List<Employee>()
            {
                new Employee{ ID = 101, Name = "Pranaya", Gender = "Male", Salary = 100000},
                new Employee{ ID = 102, Name = "Priyanka", Gender = "Female", Salary = 200000},
                new Employee{ ID = 103, Name = "Anurag", Gender = "Male", Salary = 300000},
                new Employee{ ID = 104, Name = "Preety", Gender = "Female", Salary = 400000},
                new Employee{ ID = 104, Name = "Sambit", Gender = "Male", Salary = 500000},
            };

            //Step3
            // An anonymous method is being passed as an argument to
            // the Find() method of List Collection.
            Employee employee = listEmployees.Find(
                                    delegate (Employee x)
                                    {
                                        return x.ID == 103;
                                    }
                                );
            Console.WriteLine(@"ID : {0}, Name : {1}, Gender : {2}, Salary : {3}",
                employee.ID, employee.Name, employee.Gender, employee.Salary);

            Console.ReadKey();    
        }
    }

    // Step1
    // Create a class called Employee with
    // ID, Name, Gender and Salary Properties
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public double Salary { get; set; }
    }
}
OUTPUT:

Anonymous Method Real-Time Example in C#

Find Method:

In the above two examples, the Find() method of the generic List collection class expects a delegate to be passed as an argument. If you want to look at the signature of the Find method, then right-click on the Find() method and select “Go To Definition” from the context menu. Then you will see the following method.

public T Find(Predicate<T> match);

In the next article, I am going to discuss the Lambda Expression in C# with examples. In this article, I try to explain the Anonymous Method in C# with some examples. I hope you understood the need and use of Anonymous Methods in C#.

Leave a Reply

Your email address will not be published. Required fields are marked *