Csharp4 delegates lambda_and_events
Upcoming SlideShare
Loading in...5
×
 

Csharp4 delegates lambda_and_events

on

  • 2,138 views

 

Statistics

Views

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

Actions

Likes
0
Downloads
153
Comments
1

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel

11 of 1

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • //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("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/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 < 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("{0}, {1:C}", 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(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); } } } //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("{0}, {1:C}", 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("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); } } } }
  • //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("ProcessAndDisplayNumber called with value = {0}", 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("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/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("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"); } } } } }
  • // 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("CarDealer, new car {0}", 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("{0}: car {1} is new", name, e.Car); } } } //EventsSample/Program.cs namespace Najah.ILoveCsharp.Delegates { class Program { static void Main() { var dealer = new CarDealer(); var michael = new Consumer("Michael"); dealer.NewCarInfo += michael.NewCarIsHere; dealer.NewCar("Mercedes"); var nick = new Consumer("Nick"); dealer.NewCarInfo += nick.NewCarIsHere; dealer.NewCar("Ferrari"); dealer.NewCarInfo -= michael.NewCarIsHere; dealer.NewCar("Toyota"); } } }
  • // 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("{0}: car {1} is new", 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("Michael"); WeakCarInfoEventManager.AddListener(dealer, michael); dealer.NewCar("Mercedes"); var nick = new Consumer("Nick"); WeakCarInfoEventManager.AddListener(dealer, nick); dealer.NewCar("Ferrari"); WeakCarInfoEventManager.RemoveListener(dealer, michael); dealer.NewCar("Toyota"); } } }

Csharp4 delegates lambda_and_events Csharp4 delegates lambda_and_events Presentation 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("String is {0}", firstStringMethod ()); firstStringMethod = new GetAString( x.ToString ); Console.WriteLine("String is {0}", 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