Wednesday, July 13, 2011

Action Type

Action Type
        You can use the Action delegate to pass a method as a parameter without explicitly declaring a custom delegate. The encapsulated method must correspond to the method signature that is defined by this delegate. This means that the encapsulated method must have one parameter that is passed to it by value, and it must not return a value. (In C#, the method must return void.) Typically, such a method is used to perform an operation.
     Encapsulates a method that has a single parameter and does not return a value.

Example:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ActionTest
{
    public class Customer
    {
       public static Action<List<Customer>> 
CompletedAction {get;set;}
        public string Name;
        public string City;
 
        public Customer()
        { }
        public Customer(string name, string city)
        {
            Name = name;
            City = city;
        }
        public static void DisplayCustomers()
        {
           List<Customer> cutomerList = new List<Customer>();
           cutomerList.Add(new Customer("Junaid Ahmed""Karachi"));
           cutomerList.Add(new Customer("Asif Mughal""Sukkur"));
           cutomerList.Add(new Customer("Ali Khan""Lahore"));
         
            if(CompletedAction !=null)
                CompletedAction(cutomerList);
        }
 
    }
 
 
    class Program
    {     
 
        public static  void PrintCustomers(List<Customer> customers)
        {
            foreach (Customer customer in customers)
            {
                Console.WriteLine(
                 string.Format("Customer Name : {0}  City : {1}",
                       customer.Name, customer.City));
            }
        }
        static void Main(string[] args)
        {           
 
            // 1). You can print like this by assigning the Action
            // delegate with anonymous methods in C#
            Customer.CompletedAction =  
                  delegate(List<Customer> listCustomers) 
            {
                PrintCustomers(listCustomers);
            };
 
 
            // 2). You can print like this by assigning a
            // lambda expression to an Action delegate instance
            //Customer.CompletedAction = (listCustomers) =>
            //{
            //    PrintCustomers(listCustomers);
            //};
            //OR you can use this one same as 2.
            //Customer.CompletedAction = 
                  // listCustomers => PrintCustomers(listCustomers);
 
            Customer.DisplayCustomers();
       
            Console.ReadLine(); 
        }
    }
}
 
 
Output: 
Customer Name : Junaid Ahmed  City : Karachi
Customer Name : Asif Mughal  City : Sukkur
Customer Name : Ali Khan  City : Lahore



See msdn for details.

No comments:

Post a Comment