Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Part 98 - Anonymous methods in c#

Suggested Videos 
Part 95 - Deadlock in a multithreaded program
Part 96 - How to resolve a deadlock in a multithreaded program
Part 97 - Performance of a multithreaded program



In this video we will discuss, what anonymous methods are with an example.

What is an anonymous method?
In simple terms, anonymous method is a method without a name.



Let's understand how a method can exist without a name
using System;
using System.Collections.Generic;

class Program
{
    public static void Main()
    {
        List<Employee> listEmployees = new List<Employee>()
        {
            new Employee{ ID = 101, Name = "Mark"},
            new Employee{ ID = 102, Name = "John"},
            new Employee{ ID = 103, Name = "Mary"},
        };

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

        // Step 3: Now pass the delegate instance as
        // the argument for Find() method
        Employee employee =
            listEmployees.Find(x => predicateEmployee(x));
        Console.WriteLine("ID = {0}, Name {1}",
            employee.ID, employee.Name);

        // Anonymous method is being passed as an argument to
        // the Find() method. This anonymous method replaces
        // the need for Step 1, 2 and 3
        employee = listEmployees.Find(delegate(Employee x)
                                  { return x.ID == 102; });
        Console.WriteLine("ID = {0}, Name {1}",
            employee.ID, employee.Name);
    }

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

    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
}

In this example, Find() method expects a delegate to be passed as the argument. If you want to look at the signature of the delegate, right click on Find() method and select "Go To Definition" from the context menu. At this point you should see the following method.
public T Find(Predicate<T> match);

Right click on Predicate<T> and select  "Go To Definition"

Now you should see the signature of the Predicate delegate.
public delegate bool Predicate<in T>(T obj);

Notice that the delegate returns bool and expects an object of Type <T>. In our case T is Employee

So, to the Find() method we need to pass an instance of Predicate<Employee> delegate as an argument. Delegates are function pointers. This means when we create an instance of a delegate, we pass the name of the method as an argument to the delegate constructor. 

Step 1: Create a method whose signature matches with the signature of Predicate<Employee> delegate
private static bool FindEmployee(Employee Emp)
{
    return Emp.ID == 102;
}

Step 2: Create an instance of Predicate<Employee> delegate and pass the method name as an argument to the delegate constructor
Predicate<Employee> predicateEmployee =
    new Predicate<Employee>(FindEmployee);

Step 3: Now pass the delegate instance as the argument for Find() method
Employee employee =
    listEmployees.Find(x => predicateEmployee(x));

Anonymous methods were introduced in C# 2 and they eliminate the need for Step 1, 2 & 3, that is they provide us a way of creating delegate instances without having to write a separate method.

Now let us see, how to pass anonymous method as an argument to Find() method. 
employee = listEmployees.Find(delegate(Employee x) { return x.ID == 102; });

Subscribing for an event handler is another example
private void Form1_Load(object sender, EventArgs e)
{
    Button Button1 = new Button();
    Button1.Text = "Click Me";
    Button1.Click += new EventHandler(Button1_Click);
    this.Controls.Add(Button1);
}

void Button1_Click(object sender, EventArgs e)
{
    MessageBox.Show("Button Clicked");
}

The code above can be replaced with the following code
private void Form1_Load(object sender, EventArgs e)
{
    Button Button1 = new Button();
    Button1.Text = "Click Me";
    Button1.Click += delegate(object obj, EventArgs eventArgs)
    {
        MessageBox.Show("Button Clicked");
    };
    this.Controls.Add(Button1);
}

With anonymous Methods delegate parameters are optional. This means the below code
Button1.Click += delegate(object obj, EventArgs eventArgs)
{
    MessageBox.Show("Button Clicked");
};

can be rewritten as shown below
Button1.Click += delegate
{
    MessageBox.Show("Button Clicked");
};

1 comment:

  1. Hi Venkat
    Please give some easy example for Anonymous Methods and Lamda Expression. Thanks

    ReplyDelete

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.