Wednesday, July 13, 2011

Func Type

Func Type
        You can use the Func delegate to pass a method as a parameter without explicitly declaring a custom delegate.You can use this delegate to represent a method that can be passed 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 that it must return a value.
Encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter.
Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace FuncTest
{
    public class Customer
    {
       public static Func<List<Customer>, int>CompletedFunc{ 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 (CompletedFunc != null)
           //Func return int in this case
           Console.WriteLine("The number of customers in list are :"                         + CompletedFunc.Invoke (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 Func                           //delegate with anonymous methods in C#        
          Customer.CompletedFunc = delegate(List<Customer>
 listCustomer)
          {
              PrintCustomers(listCustomers);
              return listCustomers.Count;
          };
          // 2). You can print like this by assigning a lambda 
          //expression to a Func delegate instance
          //Customer.CompletedFunc = (listCustomers) =>
          //{
          //    PrintCustomers(listCustomers);
          //    return listCustomers.Count;
          //};
           
          Customer.DisplayCustomers();
 
           Console.ReadLine();
       }
    }
 
}
 
Output:
  
Customer Name : Junaid Ahmed  City : Karachi
Customer Name : Asif Mughal  City : Sukkur
Customer Name : Ali Khan  City : Lahore
The number of customers in list are : 3


 See msdn for details.
 

No comments:

Post a Comment