using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharpDelegate { public enum comparison { theFirstComesFirst = 1, theSecondComesFirst = 2 } // A simple class to hold two items public class Pair { // Private array to hold the two objects private object[] thePair = new object[2]; // The delegate declaration public delegate comparison WhichIsFirst(object obj1, object obj2); // Passed in constructor takes two objects, // added in order received public Pair( object firstObject, object secondObject) { thePair[0] = firstObject; thePair[1] = secondObject; } // Public method that orders the // two objects by whatever criteria the objects like! public void Sort( WhichIsFirst theDelegatedFunc) { if (theDelegatedFunc(thePair[0], thePair[1]) == comparison.theSecondComesFirst) { object temp = thePair[0]; thePair[0] = thePair[1]; thePair[1] = temp; } } // Public method that orders the // two objects by the reverse of whatever criteria the // objects likes! public void ReverseSort( WhichIsFirst theDelegatedFunc) { if (theDelegatedFunc(thePair[0], thePair[1]) == comparison.theFirstComesFirst) { object temp = thePair[0]; thePair[0] = thePair[1]; thePair[1] = temp; } } // Ask the two objects to give their string values public override string ToString() { return thePair[0].ToString() + ", " + thePair[1].ToString(); } } public class Dog { private int weight; public Dog(int weight) { this.weight = weight; } // Dogs are sorted by weight public static comparison WhichDogComesFirst( Object o1, Object o2) { Dog d1 = (Dog)o1; Dog d2 = (Dog)o2; return d1.weight > d2.weight ? comparison.theSecondComesFirst : comparison.theFirstComesFirst; } public override string ToString() { return weight.ToString(); } } class Tester { public void Run() { // Create two dogs // and add them to a Pair object Dog Milo = new Dog(65); Dog Fred = new Dog(12); Pair dogPair = new Pair(Milo, Fred); Console.WriteLine("dogPair\t\t\t\t: {0}", dogPair.ToString()); // Instantiate the delegate Pair.WhichIsFirst theDogDelegate = new Pair.WhichIsFirst( Dog.WhichDogComesFirst); // Sort using the delegate dogPair.Sort(theDogDelegate); Console.WriteLine("After Sort dogPair\t\t: {0}", dogPair.ToString()); dogPair.ReverseSort(theDogDelegate); Console.WriteLine("After ReverseSort dogPair\t: {0}", dogPair.ToString()); } static void Main() { Tester t = new Tester(); t.Run(); Console.ReadLine(); } } }