Saturday, April 30, 2011

Delegates

Probably all of us heard about 'Delegates' and 'Events' when we started learning .net programming, specially in case for an interview mostly this question is common to explain about delegate and event.
Today I am not going to give any bookish definition for delegates or events, because already we have heard million times that delegate is similar to function pointer. But when we need to implement delegates in code we really fall into a big trouble. I will try to make understand by few lines of code about how to create and call the delegate or the function pointer and I hope will be a big help for the beginners :).

 
namespace Delegates
{
public delegate int Comparer(object obj1, object obj2);


public class Name
{
public string FirstName = null;
public string LastName = null;

public Name(string first, string last)
{
FirstName = first;
LastName = last;
}
public static int CompareFirstNames(object name1, object name2)
{
string n1 = ((Name)name1).FirstName;
string n2 = ((Name)name2).FirstName;

if (String.Compare(n1, n2) > 0)
{
return 1;
}
else if (String.Compare(n1, n2) > 0)
{
return -1;
}
else
{
return 0;
}
}

public override string ToString()
{
return FirstName + " " + LastName;
}
}

class SimpleDelegate
{
Name[] names = new Name[6];

public SimpleDelegate()
{
names[0] = new Name("Rashedul", "Islam");
names[1] = new Name("Tanveer", "Rahman");
names[2] = new Name("Sarwar", "Hossain");
names[3] = new Name("Shehreen", "Haider");
names[4] = new Name("Rokon", "Rok");
names[5] = new Name("Mujahidur", "Rashid");
}

static void Main(string[] args)
{
SimpleDelegate sd = new SimpleDelegate();

Comparer cmp = new Comparer(Name.CompareFirstNames);

Console.WriteLine("\nBefore Sort: \n");

sd.PrintNames();

sd.Sort(cmp);

Console.WriteLine("\nAfter Sort: \n");

sd.PrintNames();

Console.ReadKey();
}

public void Sort(Comparer compare)
{
object temp;

for (int i = 0; i < names.Length; i++)
{
for (int j = i; j < names.Length; j++)
{
if (compare(names[i], names[j]) > 0)
{
temp = names[i];
names[i] = names[j];
names[j] = (Name)temp;
}
}
}
}

public void PrintNames()
{
Console.WriteLine("Names: \n");

foreach (Name name in names)
{
Console.WriteLine(name.ToString());
}
}
}
}

In this above example of code we have used delegate which calls a function to sort an array.

The line below is the declaration of the delegate which takes take two parameters.

public delegate int Comparer(object obj1, object obj2);

In the class name there is method named 'CompareFirstNames' which takes two arguments and compares the string and also returns a integer value. Actually we are going to pointing on this method by our declared delegate 'Comparer'.
Well now its time to instantiate the delegate and call the method using the delegate. If we look at the 'Main' method we can find how the delegate has been instantiated.

Comparer cmp = new Comparer(Name.CompareFirstNames);

Look carefully the above line, we did not used two object type parameters rather we passed a method who take similarly two object type parameters. So our new instance of delegate 'cmp' is pointing to the method 'CompareFirstNames' method.

Now we called the 'sort' method which takes a delegate type argument.

sd.Sort(cmp);

In the 'sort' method, compare is simply used as a function which returns an integer value to compare.

If you run the above chunk of code and debug then I hope you concept will be more clear on how delegate works.

I hope this post will be helpful understand delegate mechanism and in the very next post I will try to add similarly simple example on another .net feature Event.

No comments:

Post a Comment

Rest Service using WEB API C#

This post will show a simple example of REST service built on Micrsoft WEB API framework. WEB API is an extensible framework from microsof...