HI WELCOME TO SIRIS

Anonymous methods in c#

Leave a Comment
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 EmployeeID = 101Name = "Mark"},
            new EmployeeID = 102Name = "John"},
            new EmployeeID = 103Name = "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.IDemployee.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.IDemployee.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 { getset; }
        public string Name { getset; }
    }
}

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 senderEventArgs e)
{
    Button Button1 = new Button();
    Button1.Text = "Click Me";
    Button1.Click += new EventHandler(Button1_Click);
    this.Controls.Add(Button1);
}

void Button1_Click(object senderEventArgs e)
{
    MessageBox.Show("Button Clicked");
}

The code above can be replaced with the following code
private void Form1_Load(object senderEventArgs e)
{
    Button Button1 = new Button();
    Button1.Text = "Click Me";
    Button1.Click += delegate(object objEventArgs 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 objEventArgs eventArgs)
{
    MessageBox.Show("Button Clicked");
};

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

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.