4 September 2011

Built-in General Purpose Delegates in .NET

In day-to-day coding, we often need to create delegates. Every time we need a delegate, we usually create a new delegate and use it. But, if you know .NET already provides some ready made delegates which we can use for varying purposes. So, in this post I will be discussing some of the common built-in delegates that we can use for general purpose.

System.Action: The Action delegate can accept any method which takes zero arguments and returns void. The declaration goes like

public delegate void Action();
System.Action<…> : This is a generic version of System.Action delegate. This delegate can accept any method that takes 1 to 16 parameters and returns void. You can use this delegate as below,

public void SomeMethod(int a, string b, double c){}
System.Action<int, string , double> action = new System.Action<int, string , double>( SomeMethod );

System.Comparison<T>: Actually this delegate is used for specific purpose, I am discussing this here because it is often used in Sorting techniques.  This takes a method as parameter which takes two arguments of type T and return an Integer. For example, I want to sort list of employees based on their first names then I can do it as,

private int CompareEmpoyees(Employee a, Employee b)
{
     return a.FirstName.CompareTo(b.FirstName);
}

ListempList = GetEmployeeList();
Comparison comparer = new Comparison(CompareEmpoyees);
empList.Sort(comparer);


System.Func<…, out TOut> : This is a generic delegate that accepts any method that takes 0 to 16 arguments of any type and return an argument of type TOut. For example,

public Employee SomeMethod(int a, string b, double c)
{
}

System.Action<int, string , double> action = new System.Action<int, string , double, Employee>( SomeMethod );

System.MethodInvoker: This delegate is similar to System.Action delegate which accepts a method that takes zero arguments and returns void. But, as the name suggests, this delegate is used at places where you need to talk to UI elements from a background thread. Something like below,

MethodInvoker mi = new MethodInvoker ( () => { textBox1.Text = "Hello World"; });
this.Invoke(mi);


That is it for now. I will be editing this page if I find any other delegates that fit here. Meanwhile, If you want me to add anything here, please let me know.

4 comments: