GetAStringDemo
using System;namespace Wrox.ProCSharp.Delegates{ class Program { private delegate string GetAString(); static void Main() { int x = 40; GetAString firstStringMethod = x.ToString; Console.WriteLine("String is {0}", firstStringMethod()); Currency balance = new Currency(34, 50); // firstStringMethod references an instance method firstStringMethod = balance.ToString; Console.WriteLine("String is {0}", firstStringMethod()); // firstStringMethod references a static method firstStringMethod = new GetAString(Currency.GetCurrencyUnit); Console.WriteLine("String is {0}", firstStringMethod()); } }}
namespace Wrox.ProCSharp.Delegates{ struct Currency { public uint Dollars; public ushort Cents; public Currency(uint dollars, ushort cents) { this.Dollars = dollars; this.Cents = cents; } public override string ToString() { return string.Format("${0}.{1,-2:00}", Dollars, Cents); } public static string GetCurrencyUnit() { return "Dollar"; } public static explicit operator Currency(float value) { checked { uint dollars = (uint)value; ushort cents = (ushort)((value - dollars) * 100); return new Currency(dollars, cents); } } public static implicit operator float(Currency value) { return value.Dollars + (value.Cents / 100.0f); } public static implicit operator Currency(uint value) { return new Currency(value, 0); } public static implicit operator uint(Currency value) { return value.Dollars; } }}
SimpleDelegates
namespace Wrox.ProCSharp.Delegates{ class MathOperations { public static double MultiplyByTwo(double value) { return value * 2; } public static double Square(double value) { return value * value; } }}
using System;namespace Wrox.ProCSharp.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("Using operations[{0}]:", 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( "Value is {0}, result of operation is {1}", value, result); } }}
BubbleSorter
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Wrox.ProCSharp.Delegates{ class Program { static void Main() { Employee[] employees = { new Employee("Bugs Bunny", 20000), new Employee("Elmer Fudd", 10000), new Employee("Daffy Duck", 25000), new Employee("Wile Coyote", 1000000.38m), new Employee("Foghorn Leghorn", 23000), new Employee("RoadRunner", 50000) }; BubbleSorter.Sort(employees, Employee.CompareSalary); foreach (var employee in employees) { Console.WriteLine(employee); } } }}
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Wrox.ProCSharp.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("{0}, {1:C}", Name, Salary); } public static bool CompareSalary(Employee e1, Employee e2) { return e1.Salary < e2.Salary; } }}
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Wrox.ProCSharp.Delegates{ class BubbleSorter { static public void Sort(IList sortArray, Func 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); } }}
MulticastDelegates
using System;namespace Wrox.ProCSharp.Delegates{ class Program { static void Main() { Actionoperations = MathOperations.MultiplyByTwo; operations += MathOperations.Square; ProcessAndDisplayNumber(operations, 2.0); ProcessAndDisplayNumber(operations, 7.94); ProcessAndDisplayNumber(operations, 1.414); Console.WriteLine(); } static void ProcessAndDisplayNumber(Action action, double value) { Console.WriteLine(); Console.WriteLine("ProcessAndDisplayNumber called with value = {0}", value); action(value); } }}
using System;namespace Wrox.ProCSharp.Delegates{ class MathOperations { public static void MultiplyByTwo(double value) { double result = value * 2; Console.WriteLine("Multiplying by 2: {0} gives {1}", value, result); } public static void Square(double value) { double result = value * value; Console.WriteLine("Squaring: {0} gives {1}", value, result); } }}
MulticastDelegateWithIteration
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Wrox.ProCSharp.Delegates{ class Program { static void One() { Console.WriteLine("One"); throw new Exception("Error in one"); } static void Two() { Console.WriteLine("Two"); } static void Main() { //Action d1 = One; //d1 += Two; //try //{ // d1(); //} //catch (Exception) //{ // Console.WriteLine("Exception caught"); //} Action d1 = One; d1 += Two; Delegate[] delegates = d1.GetInvocationList(); foreach (Action d in delegates) { try { d(); } catch (Exception) { Console.WriteLine("Exception caught"); } } } }}
AnonymousMethods
using System;namespace Wrox.ProCSharp.Delegates{ class Program { static void Main() { string mid = ", middle part,"; FuncanonDel = delegate(string param) { param += mid; param += " and this was added to the string."; return param; }; Console.WriteLine(anonDel("Start of string")); } }}
LambdaExpressions
using System;namespace Wrox.ProCSharp.Delegates{ class Program { static void Main() { // SimpleDemos(); int someVal = 5; Funcf = x => x + someVal; someVal = 7; Console.WriteLine(f(3)); } static void SimpleDemos() { Func oneParam = s => String.Format("change uppercase {0}", s.ToUpper()); Console.WriteLine(oneParam("test")); Func twoParams = (x, y) => x * y; Console.WriteLine(twoParams(3, 2)); Func twoParamsWithTypes = (double x, double y) => x * y; Console.WriteLine(twoParamsWithTypes(4, 2)); Func operations = x => x * 2; operations += x => x * x; ProcessAndDisplayNumber(operations, 2.0); ProcessAndDisplayNumber(operations, 7.94); ProcessAndDisplayNumber(operations, 1.414); Console.WriteLine(); } static void ProcessAndDisplayNumber(Func action, double value) { double result = action(value); Console.WriteLine( "Value is {0}, result of operation is {1}", value, result); } }}
EventsSample
using System;namespace Wrox.ProCSharp.Delegates{ public class CarInfoEventArgs : EventArgs { public CarInfoEventArgs(string car) { this.Car = car; } public string Car { get; private set; } } public class CarDealer { public event EventHandlerNewCarInfo; public void NewCar(string car) { Console.WriteLine("CarDealer, new car {0}", car); RaiseNewCarInfo(car); } protected virtual void RaiseNewCarInfo(string car) { EventHandler newCarInfo = NewCarInfo; if (newCarInfo != null) { newCarInfo(this, new CarInfoEventArgs(car)); } } }}
using System;namespace Wrox.ProCSharp.Delegates{ public class Consumer { private string name; public Consumer(string name) { this.name = name; } public void NewCarIsHere(object sender, CarInfoEventArgs e) { Console.WriteLine("{0}: car {1} is new", name, e.Car); } }}
namespace Wrox.ProCSharp.Delegates{ class Program { static void Main() { var dealer = new CarDealer(); var michael = new Consumer("Michael"); dealer.NewCarInfo += michael.NewCarIsHere; dealer.NewCar("Ferrari"); var nick = new Consumer("Sebastian"); dealer.NewCarInfo += nick.NewCarIsHere; dealer.NewCar("Mercedes"); dealer.NewCarInfo -= michael.NewCarIsHere; dealer.NewCar("Red Bull Racing"); } }}
WeakEventsSample
using System.Windows;namespace Wrox.ProCSharp.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; } }}
namespace Wrox.ProCSharp.Delegates{ class Program { static void Main() { var dealer = new CarDealer(); var michael = new Consumer("Michael"); WeakCarInfoEventManager.AddListener(dealer, michael); dealer.NewCar("Mercedes"); var sebastian = new Consumer("Sebastian"); WeakCarInfoEventManager.AddListener(dealer, sebastian); dealer.NewCar("Ferrari"); WeakCarInfoEventManager.RemoveListener(dealer, michael); dealer.NewCar("Red Bull Racing"); } }}
using System;using System.Windows;namespace Wrox.ProCSharp.Delegates{ public class Consumer : IWeakEventListener { private string name; public Consumer(string name) { this.name = name; } public void NewCarIsHere(object sender, CarInfoEventArgs e) { Console.WriteLine("{0}: car {1} is new", name, e.Car); } bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e) { NewCarIsHere(sender, e as CarInfoEventArgs); return true; } }}
using System;namespace Wrox.ProCSharp.Delegates{ public class CarInfoEventArgs : EventArgs { public CarInfoEventArgs(string car) { this.Car = car; } public string Car { get; private set; } } public class CarDealer { public event EventHandlerNewCarInfo; public CarDealer() { } public void NewCar(string car) { Console.WriteLine("CarDealer, new car {0}", car); if (NewCarInfo != null) { NewCarInfo(this, new CarInfoEventArgs(car)); } } }}