Anonymous Method Real-Time Example in C#

Anonymous Method Real-Time Example in C#

In this article, I am going to discuss the Anonymous method real-time example in C#. Please read our previous articles before proceeding to this article where we discussed the Generic Delegates in C# with some examples.

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 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 Arrays in C# with some examples. Here, in this article, I try to explain the Anonymous Method Real-Time Example in C#. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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