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);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);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