Upcoming SlideShare
×

Like this presentation? Why not share!

# Csharp4 delegates lambda_and_events

## on Apr 29, 2011

• 2,138 views

### Views

Total Views
2,138
Views on SlideShare
2,138
Embed Views
0

Likes
0
153
1

No embeds

### Report content

11 of 1

• Comment goes here.
Are you sure you want to
• thanks
Are you sure you want to
• //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 &lt; 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(IList sortArray, Func comparison) { bool swapped = true; do { swapped = false; for (int i = 0; i &lt; 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 &lt; 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(IList sortArray, Func comparison) { bool swapped = true; do { swapped = false; for (int i = 0; i &lt; 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 &lt; 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 operations = 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(&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 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;); } } }

## Csharp4 delegates lambda_and_eventsPresentation Transcript

• Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com
• Delegates, Lambdas, and Events Prepared By : Abed ElAzeem Bukhari What ‘s in this chapter? ➤ Delegates ➤ Lambda expressions ➤ Events
• Delegates private delegate string GetAString(); static void Main() { int x = 40; GetAString firstStringMethod = x.ToString; Console.WriteLine(&quot;String is {0}&quot;, firstStringMethod ()); firstStringMethod = new GetAString( x.ToString ); Console.WriteLine(&quot;String is {0}&quot;, firstStringMethod()); }
• Delegates cont. SimpleDelegate/MathOperations.cs SimpleDelegate/Program.cs
• Action<T> and Func<T> delegates delegate double DoubleOp(double x); Func<double, double> [] operations = { MathOperations.MultiplyByTwo, MathOperations.Square }; static void ProcessAndDisplayNumber( Func<double, double> action , double value) { double result = action (value); Console.WriteLine( &quot;Value is {0}, result of operation is {1}&quot;, value, result); }
• BubbleSorter example BubbleSorter/BubbleSorter.cs BubbleSorter/Employee.cs
• 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
• 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.
• Multicast delegates cont static void Main() { Action d1 = One; d1 += Two; Delegate[] delegates = d1. GetInvocationList (); foreach (Action d in delegates) { try { d(); } catch (Exception) { Console.WriteLine(&quot;Exception caught&quot;); } } }
• Anonymous methods AnonymousMethods/Program.cs
• 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
• Lambda Expressions Parameters Func<string, string> oneParam = s => String.Format( &quot;change uppercase {0}&quot;, s.ToUpper()); Console.WriteLine(oneParam(&quot;test&quot;)); Func<double, double, double> twoParams = (x, y) => x * y; Console.WriteLine(twoParams(3, 2)); Func<double, double, double> twoParamsWithTypes = (double x, double y) => x * y; Console.WriteLine(twoParamsWithTypes(4, 2));
• 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
• 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; } }
• 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”
• 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.
• 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
• Event Publisher cont private delegate EventHandler <CarInfoEventArgs> newCarInfo; public event EventHandler <CarInfoEventArgs> NewCarInfo { add { newCarInfo += value; } remove { newCarInfo = value; } }
• 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(&quot;CarDealer, new car {0}&quot;, car); if (NewCarInfo != null ) { NewCarInfo(this, new CarInfoEventArgs(car)); } }
• Event listener EventsSample/Consumer.cs EventsSample/Program.cs
• Weak events WeakEventsSample/WeakCarInfoEventManager.cs Event Listner WeakEventsSample/Consumer.cs WeakEventsSample/Program.cs
• Thanks For Attending Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com