SlideShare ist ein Scribd-Unternehmen logo
1 von 22
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

Weitere ähnliche Inhalte

Was ist angesagt?

C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
Jussi Pohjolainen
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
Tech_MX
 

Was ist angesagt? (20)

Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function
 
escape sequences and substitution markers
escape sequences and substitution markersescape sequences and substitution markers
escape sequences and substitution markers
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++
 
pointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpppointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpp
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
 
C++11
C++11C++11
C++11
 
C important questions
C important questionsC important questions
C important questions
 
Pointers
PointersPointers
Pointers
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
 
Csharp generics
Csharp genericsCsharp generics
Csharp generics
 
Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++
 
Virtual function
Virtual functionVirtual function
Virtual function
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
constructors and destructors in c++
constructors and destructors in c++constructors and destructors in c++
constructors and destructors in c++
 
C Theory
C TheoryC Theory
C Theory
 
Scala functions
Scala functionsScala functions
Scala functions
 
7 functions
7  functions7  functions
7 functions
 
Lecture 13 - Storage Classes
Lecture 13 - Storage ClassesLecture 13 - Storage Classes
Lecture 13 - Storage Classes
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 

Andere mochten auch (9)

Whats New In C# 3.0
Whats New In C# 3.0Whats New In C# 3.0
Whats New In C# 3.0
 
Secure mvc application saineshwar
Secure mvc application   saineshwarSecure mvc application   saineshwar
Secure mvc application saineshwar
 
Csharp4 arrays and_tuples
Csharp4 arrays and_tuplesCsharp4 arrays and_tuples
Csharp4 arrays and_tuples
 
C# language
C# languageC# language
C# language
 
Free MVC project to learn for beginners.
Free MVC project to learn for beginners.Free MVC project to learn for beginners.
Free MVC project to learn for beginners.
 
Csharp4 basics
Csharp4 basicsCsharp4 basics
Csharp4 basics
 
C# 3.5 Features
C# 3.5 FeaturesC# 3.5 Features
C# 3.5 Features
 
Introduction to .NET Core & ASP.NET Core MVC
Introduction to .NET Core & ASP.NET Core MVCIntroduction to .NET Core & ASP.NET Core MVC
Introduction to .NET Core & ASP.NET Core MVC
 
Introduction to C# 6.0 and 7.0
Introduction to C# 6.0 and 7.0Introduction to C# 6.0 and 7.0
Introduction to C# 6.0 and 7.0
 

Ähnlich wie Csharp4 delegates lambda_and_events

Delegates and events
Delegates and eventsDelegates and events
Delegates and events
Iblesoft
 
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraLambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Jaliya Udagedara
 
C++ Function
C++ FunctionC++ Function
C++ Function
Hajar
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
g_hemanth17
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1
Sachin Singh
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
Raga Vahini
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
Satish Verma
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
singhadarsh
 

Ähnlich wie Csharp4 delegates lambda_and_events (20)

C# Delegates
C# DelegatesC# Delegates
C# Delegates
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
 
Delegates and events
Delegates and eventsDelegates and events
Delegates and events
 
PROGRAMMING USING C#.NET SARASWATHI RAMALINGAM
PROGRAMMING USING C#.NET SARASWATHI RAMALINGAMPROGRAMMING USING C#.NET SARASWATHI RAMALINGAM
PROGRAMMING USING C#.NET SARASWATHI RAMALINGAM
 
Can't Dance The Lambda
Can't Dance The LambdaCan't Dance The Lambda
Can't Dance The Lambda
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
 
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraLambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
tutorials-c-sharp_understanding-generic-anonymous-methods-and-lambda-expressi...
tutorials-c-sharp_understanding-generic-anonymous-methods-and-lambda-expressi...tutorials-c-sharp_understanding-generic-anonymous-methods-and-lambda-expressi...
tutorials-c-sharp_understanding-generic-anonymous-methods-and-lambda-expressi...
 
Cs30 New
Cs30 NewCs30 New
Cs30 New
 
Delegates and events
Delegates and events   Delegates and events
Delegates and events
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
 
Matlab Basic Tutorial
Matlab Basic TutorialMatlab Basic Tutorial
Matlab Basic Tutorial
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 

Mehr von Abed Bukhari

Csharp4 strings and_regular_expressions
Csharp4 strings and_regular_expressionsCsharp4 strings and_regular_expressions
Csharp4 strings and_regular_expressions
Abed Bukhari
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
Abed Bukhari
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
Abed Bukhari
 
Csharp4 inheritance
Csharp4 inheritanceCsharp4 inheritance
Csharp4 inheritance
Abed Bukhari
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
Abed Bukhari
 

Mehr von Abed Bukhari (6)

Csharp4 generics
Csharp4 genericsCsharp4 generics
Csharp4 generics
 
Csharp4 strings and_regular_expressions
Csharp4 strings and_regular_expressionsCsharp4 strings and_regular_expressions
Csharp4 strings and_regular_expressions
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
 
Csharp4 inheritance
Csharp4 inheritanceCsharp4 inheritance
Csharp4 inheritance
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 

Csharp4 delegates lambda_and_events

  • 1. Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com
  • 2. Delegates, Lambdas, and Events Prepared By : Abed ElAzeem Bukhari What ‘s in this chapter? ➤ Delegates ➤ Lambda expressions ➤ Events
  • 3. 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()); }
  • 5. 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); }
  • 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.
  • 9. 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;); } } }
  • 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
  • 12. 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));
  • 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
  • 18. Event Publisher cont private delegate EventHandler <CarInfoEventArgs> newCarInfo; public event EventHandler <CarInfoEventArgs> NewCarInfo { add { newCarInfo += value; } remove { newCarInfo = value; } }
  • 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(&quot;CarDealer, new car {0}&quot;, car); if (NewCarInfo != null ) { NewCarInfo(this, new CarInfoEventArgs(car)); } }
  • 20. Event listener EventsSample/Consumer.cs EventsSample/Program.cs
  • 21. Weak events WeakEventsSample/WeakCarInfoEventManager.cs Event Listner WeakEventsSample/Consumer.cs WeakEventsSample/Program.cs
  • 22. Thanks For Attending Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com

Hinweis der Redaktion

  1. //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(&amp;quot;Using operations[{0}]:&amp;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( &amp;quot;Value is {0}, result of operation is {1}&amp;quot;, value, result); } } }
  2. //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&lt;T&gt;(IList&lt;T&gt; sortArray, Func&lt;T, T, bool&gt; 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(&amp;quot;{0}, {1:C}&amp;quot;, Name, Salary); } public static bool CompareSalary(Employee e1, Employee e2) { return e1.Salary &lt; e2.Salary; } } }
  3. //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&lt;T&gt;(IList&lt;T&gt; sortArray, Func&lt;T, T, bool&gt; 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(&amp;quot;{0}, {1:C}&amp;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(&amp;quot;Bugs Bunny&amp;quot;, 20000), new Employee(&amp;quot;Elmer Fudd&amp;quot;, 10000), new Employee(&amp;quot;Daffy Duck&amp;quot;, 25000), new Employee(&amp;quot;Wile Coyote&amp;quot;, 1000000.38m), new Employee(&amp;quot;Foghorn Leghorn&amp;quot;, 23000), new Employee(&amp;quot;RoadRunner&amp;quot;, 50000) }; BubbleSorter.Sort(employees, Employee.CompareSalary); foreach (var employee in employees) { Console.WriteLine(employee); } } } }
  4. //MulticastDelegates/Program.cs using System; namespace Najah.ILoveCsharp.Delegates { class Program { static void Main() { Action&lt;double&gt; operations = MathOperations.MultiplyByTwo; operations += MathOperations.Square; ProcessAndDisplayNumber(operations, 2.0); ProcessAndDisplayNumber(operations, 7.94); ProcessAndDisplayNumber(operations, 1.414); Console.WriteLine(); } static void ProcessAndDisplayNumber(Action&lt;double&gt; action, double value) { Console.WriteLine(); Console.WriteLine(&amp;quot;ProcessAndDisplayNumber called with value = {0}&amp;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(&amp;quot;Multiplying by 2: {0} gives {1}&amp;quot;, value, result); } public static void Square(double value) { double result = value * value; Console.WriteLine(&amp;quot;Squaring: {0} gives {1}&amp;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(&amp;quot;One&amp;quot;); throw new Exception(&amp;quot;Error in one&amp;quot;); } static void Two() { Console.WriteLine(&amp;quot;Two&amp;quot;); } static void Main() { //Action d1 = One; //d1 += Two; //try //{ // d1(); //} //catch (Exception) //{ // Console.WriteLine(&amp;quot;Exception caught&amp;quot;); //} Action d1 = One; d1 += Two; Delegate[] delegates = d1.GetInvocationList(); foreach (Action d in delegates) { try { d(); } catch (Exception) { Console.WriteLine(&amp;quot;Exception caught&amp;quot;); } } } } }
  5. // 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&lt;CarInfoEventArgs&gt; NewCarInfo; public void NewCar(string car) { Console.WriteLine(&amp;quot;CarDealer, new car {0}&amp;quot;, car); if (NewCarInfo != null) { NewCarInfo(this, new CarInfoEventArgs(car)); } } } }
  6. //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(&amp;quot;{0}: car {1} is new&amp;quot;, name, e.Car); } } } //EventsSample/Program.cs namespace Najah.ILoveCsharp.Delegates { class Program { static void Main() { var dealer = new CarDealer(); var michael = new Consumer(&amp;quot;Michael&amp;quot;); dealer.NewCarInfo += michael.NewCarIsHere; dealer.NewCar(&amp;quot;Mercedes&amp;quot;); var nick = new Consumer(&amp;quot;Nick&amp;quot;); dealer.NewCarInfo += nick.NewCarIsHere; dealer.NewCar(&amp;quot;Ferrari&amp;quot;); dealer.NewCarInfo -= michael.NewCarIsHere; dealer.NewCar(&amp;quot;Toyota&amp;quot;); } } }
  7. // 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(&amp;quot;{0}: car {1} is new&amp;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(&amp;quot;Michael&amp;quot;); WeakCarInfoEventManager.AddListener(dealer, michael); dealer.NewCar(&amp;quot;Mercedes&amp;quot;); var nick = new Consumer(&amp;quot;Nick&amp;quot;); WeakCarInfoEventManager.AddListener(dealer, nick); dealer.NewCar(&amp;quot;Ferrari&amp;quot;); WeakCarInfoEventManager.RemoveListener(dealer, michael); dealer.NewCar(&amp;quot;Toyota&amp;quot;); } } }