7. BubbleSorter example bool swapped = true; do { swapped = false; for (int i = 0; i < sortArray.Length — 1; i++) { if (sortArray[i] < sortArray[i+1])) // problem with this test { int temp = sortArray[i]; sortArray[i] = sortArray[i + 1]; sortArray[i + 1] = temp; swapped = true; } } } while (swapped); BubbleSorter/BubbleSorter.cs BubbleSorter/Employee.cs BubbleSorter/Program.cs
8. Multicast delegates Action <double> operations = MathOperations.MultiplyByTwo; operations += MathOperations.Square; MulticastDelegates/Program.cs MulticastDelegates/MathOperations.cs MulticastDelegateWithIteration/Program.cs Action < double > operation1 = MathOperations.MultiplyByTwo; Action < double > operation2 = MathOperations.Square; Action < double > operations = operation1 + operation2; //Multicast delegates also recognize the operators – and - = to remove method calls from the delegate.
11. Lambda Expressions Since C# 3.0, you can use a new syntax for assigning code implementation to delegates: Lambda expressions. Lambda expressions can be used whenever you have a delegate parameter type. The previous example using anonymous methods is changed here to use a Lambda expression. LambdaExpressions/Program.cs
13. Variables outside of the lambda expression int someVal = 5; Func < int, int > f = x => x + someVal; someVal = 7; Console.WriteLine(f(3)); // The result here invoking f(3) is 10
14. Variables outside of the lambda expression cont With the Lambda expression x = > x + someVal the compiler creates an anonymous class that has a constructor to pass the outer variable. The constructor depends on how many variables you access from the outside public class AnonymousClass { private int someVal; public AnonymousClass(int someVal) { this.someVal = someVal; } public int AnonymousMethod(int x) { return x + someVal; } }
15. Variables outside of the lambda expression cont Lambda expressions can be used any place where the type is a delegate. Another use of Lambda expressions is when the type is Expression or Expression <T> . Here the compiler creates an expression tree. This feature is discussed in “ Language Integrated Query. ( LINQ ) Lecture”
16. Events Events are based on delegates and offer a publish/subscribe mechanism to delegates. You can find events everywhere across the framework. In Windows applications, the Button class offers the Click event. This type of event is a delegate. A handler method that is invoked when the Click event is fired needs to be defined, with the parameters as defined by the delegate type.
17. Event Publisher EventsSample/CarDealer.cs The delegate EventHandler < TEventArgs > is defi ned as follows: public delegate void EventHandler <TEventArgs> (object sender, TEventArgs e) where TEventArgs: EventArgs
19. Event Publisher cont Before firing the event, it is necessary to check whether the delegate NewCarInfo is not null . If no one subscribed, the delegate is null : public void NewCar(string car) { Console.WriteLine("CarDealer, new car {0}", car); if (NewCarInfo != null ) { NewCarInfo(this, new CarInfoEventArgs(car)); } }
//SimpleDelegate/MathOperations.cs namespace Najah.ILoveCsharp.Delegates { class MathOperations { public static double MultiplyByTwo(double value) { return value * 2; } public static double Square(double value) { return value * value; } } } //SimpleDelegate/Program.cs using System; namespace Najah.ILoveCsharp.Delegates { delegate double DoubleOp(double x); class Program { static void Main() { DoubleOp[] operations = { MathOperations.MultiplyByTwo, MathOperations.Square }; for (int i = 0; i < operations.Length; i++) { Console.WriteLine(&quot;Using operations[{0}]:&quot;, i); ProcessAndDisplayNumber(operations[i], 2.0); ProcessAndDisplayNumber(operations[i], 7.94); ProcessAndDisplayNumber(operations[i], 1.414); Console.WriteLine(); } } static void ProcessAndDisplayNumber(DoubleOp action, double value) { double result = action(value); Console.WriteLine( &quot;Value is {0}, result of operation is {1}&quot;, value, result); } } }
//BubbleSorter/BubbleSorter.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Delegates { class BubbleSorter { static public void Sort<T>(IList<T> sortArray, Func<T, T, bool> comparison) { bool swapped = true; do { swapped = false; for (int i = 0; i < sortArray.Count - 1; i++) { if (comparison(sortArray[i+1], sortArray[i])) { T temp = sortArray[i]; sortArray[i] = sortArray[i + 1]; sortArray[i + 1] = temp; swapped = true; } } } while (swapped); } } } //BubbleSorter/Employee.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Delegates { class Employee { public Employee(string name, decimal salary) { this.Name = name; this.Salary = salary; } public string Name { get; private set; } public decimal Salary { get; private set; } public override string ToString() { return string.Format(&quot;{0}, {1:C}&quot;, Name, Salary); } public static bool CompareSalary(Employee e1, Employee e2) { return e1.Salary < e2.Salary; } } }
//BubbleSorter/BubbleSorter.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Delegates { class BubbleSorter { static public void Sort<T>(IList<T> sortArray, Func<T, T, bool> comparison) { bool swapped = true; do { swapped = false; for (int i = 0; i < sortArray.Count - 1; i++) { if (comparison(sortArray[i+1], sortArray[i])) { T temp = sortArray[i]; sortArray[i] = sortArray[i + 1]; sortArray[i + 1] = temp; swapped = true; } } } while (swapped); } } } //BubbleSorter/Employee.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Delegates { class Employee { public Employee(string name, decimal salary) { this.Name = name; this.Salary = salary; } public string Name { get; private set; } public decimal Salary { get; private set; } public override string ToString() { return string.Format(&quot;{0}, {1:C}&quot;, Name, Salary); } public static bool CompareSalary(Employee e1, Employee e2) { return e1.Salary < e2.Salary; } } } //BubbleSorter/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Delegates { class Program { static void Main() { Employee[] employees = { new Employee(&quot;Bugs Bunny&quot;, 20000), new Employee(&quot;Elmer Fudd&quot;, 10000), new Employee(&quot;Daffy Duck&quot;, 25000), new Employee(&quot;Wile Coyote&quot;, 1000000.38m), new Employee(&quot;Foghorn Leghorn&quot;, 23000), new Employee(&quot;RoadRunner&quot;, 50000) }; BubbleSorter.Sort(employees, Employee.CompareSalary); foreach (var employee in employees) { Console.WriteLine(employee); } } } }
//MulticastDelegates/Program.cs using System; namespace Najah.ILoveCsharp.Delegates { class Program { static void Main() { Action<double> operations = MathOperations.MultiplyByTwo; operations += MathOperations.Square; ProcessAndDisplayNumber(operations, 2.0); ProcessAndDisplayNumber(operations, 7.94); ProcessAndDisplayNumber(operations, 1.414); Console.WriteLine(); } static void ProcessAndDisplayNumber(Action<double> action, double value) { Console.WriteLine(); Console.WriteLine(&quot;ProcessAndDisplayNumber called with value = {0}&quot;, value); action(value); } } } //MulticastDelegates/MathOperations.cs using System; namespace Najah.ILoveCsharp.Delegates { class MathOperations { public static void MultiplyByTwo(double value) { double result = value * 2; Console.WriteLine(&quot;Multiplying by 2: {0} gives {1}&quot;, value, result); } public static void Square(double value) { double result = value * value; Console.WriteLine(&quot;Squaring: {0} gives {1}&quot;, value, result); } } } //MulticastDelegateWithIteration/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Delegates { class Program { static void One() { Console.WriteLine(&quot;One&quot;); throw new Exception(&quot;Error in one&quot;); } static void Two() { Console.WriteLine(&quot;Two&quot;); } static void Main() { //Action d1 = One; //d1 += Two; //try //{ // d1(); //} //catch (Exception) //{ // Console.WriteLine(&quot;Exception caught&quot;); //} Action d1 = One; d1 += Two; Delegate[] delegates = d1.GetInvocationList(); foreach (Action d in delegates) { try { d(); } catch (Exception) { Console.WriteLine(&quot;Exception caught&quot;); } } } } }
// EventsSample/CarDealer.cs using System; namespace Najah.ILoveCsharp.Delegates { public class CarInfoEventArgs : EventArgs { public CarInfoEventArgs(string car) { this.Car = car; } public string Car { get; private set; } } public class CarDealer { public event EventHandler<CarInfoEventArgs> NewCarInfo; public void NewCar(string car) { Console.WriteLine(&quot;CarDealer, new car {0}&quot;, car); if (NewCarInfo != null) { NewCarInfo(this, new CarInfoEventArgs(car)); } } } }
//EventsSample/Consumer.cs using System; namespace Najah.ILoveCsharp.Delegates { public class Consumer { private string name; public Consumer(string name) { this.name = name; } public void NewCarIsHere(object sender, CarInfoEventArgs e) { Console.WriteLine(&quot;{0}: car {1} is new&quot;, name, e.Car); } } } //EventsSample/Program.cs namespace Najah.ILoveCsharp.Delegates { class Program { static void Main() { var dealer = new CarDealer(); var michael = new Consumer(&quot;Michael&quot;); dealer.NewCarInfo += michael.NewCarIsHere; dealer.NewCar(&quot;Mercedes&quot;); var nick = new Consumer(&quot;Nick&quot;); dealer.NewCarInfo += nick.NewCarIsHere; dealer.NewCar(&quot;Ferrari&quot;); dealer.NewCarInfo -= michael.NewCarIsHere; dealer.NewCar(&quot;Toyota&quot;); } } }
// WeakEventsSample/WeakCarInfoEventManager.cs using System.Windows; namespace Najah.ILoveCsharp.Delegates { public class WeakCarInfoEventManager : WeakEventManager { public static void AddListener(object source, IWeakEventListener listener) { CurrentManager.ProtectedAddListener(source, listener); } public static void RemoveListener(object source, IWeakEventListener listener) { CurrentManager.ProtectedRemoveListener(source, listener); } public static WeakCarInfoEventManager CurrentManager { get { WeakCarInfoEventManager manager = GetCurrentManager(typeof(WeakCarInfoEventManager)) as WeakCarInfoEventManager; if (manager == null) { manager = new WeakCarInfoEventManager(); SetCurrentManager(typeof(WeakCarInfoEventManager), manager); } return manager; } } protected override void StartListening(object source) { (source as CarDealer).NewCarInfo += CarDealer_NewCarInfo; } void CarDealer_NewCarInfo(object sender, CarInfoEventArgs e) { DeliverEvent(sender, e); } protected override void StopListening(object source) { (source as CarDealer).NewCarInfo -= CarDealer_NewCarInfo; } } } //WeakEventsSample/Consumer.cs using System; using System.Windows; namespace Najah.ILoveCsharp.Delegates { public class Consumer : IWeakEventListener { private string name; public Consumer(string name) { this.name = name; } public void NewCarIsHere(object sender, CarInfoEventArgs e) { Console.WriteLine(&quot;{0}: car {1} is new&quot;, name, e.Car); } bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e) { NewCarIsHere(sender, e as CarInfoEventArgs); return true; } } } //WeakEventsSample/Program.cs namespace Najah.ILoveCsharp.Delegates { class Program { static void Main() { var dealer = new CarDealer(); var michael = new Consumer(&quot;Michael&quot;); WeakCarInfoEventManager.AddListener(dealer, michael); dealer.NewCar(&quot;Mercedes&quot;); var nick = new Consumer(&quot;Nick&quot;); WeakCarInfoEventManager.AddListener(dealer, nick); dealer.NewCar(&quot;Ferrari&quot;); WeakCarInfoEventManager.RemoveListener(dealer, michael); dealer.NewCar(&quot;Toyota&quot;); } } }