Upload
abed-elazeem-bukhari
View
2.138
Download
0
Tags:
Embed Size (px)
Citation preview
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
Delegatesprivate 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.csSimpleDelegate/Program.cs
Action<T> and Func<T> delegatesdelegate 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("Value is {0}, result of operation is {1}", value, result);}
BubbleSorter exampleBubbleSorter/BubbleSorter.csBubbleSorter/Employee.cs
BubbleSorter examplebool 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.csBubbleSorter/Employee.csBubbleSorter/Program.cs
Multicast delegatesAction <double> operations = MathOperations.MultiplyByTwo;operations += MathOperations.Square;
MulticastDelegates/Program.csMulticastDelegates/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 contstatic void Main(){Action d1 = One;d1 += Two;Delegate[] delegates = d1.GetInvocationList();foreach (Action d in delegates){ try { d(); } catch (Exception) { Console.WriteLine("Exception caught"); }}}
Anonymous methodsAnonymousMethods/Program.cs
Lambda ExpressionsSince C# 3.0, you can use a new syntax for assigning code implementation to delegates: Lambdaexpressions. Lambda expressions can be used whenever you have a delegate parameter type. The previousexample using anonymous methods is changed here to use a Lambda expression.
LambdaExpressions/Program.cs
Lambda Expressions ParametersFunc<string, string> oneParam = s => String.Format("change uppercase {0}", s.ToUpper());Console.WriteLine(oneParam("test"));
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 + someValthe 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 “ LanguageIntegrated Query. (LINQ) Lecture”
EventsEvents are based on delegates and offer a publish/subscribe mechanism to delegates. You can find eventseverywhere 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 bedefined, with the parameters as defined by the delegate type.
Event PublisherEventsSample/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 contprivate delegate EventHandler <CarInfoEventArgs> newCarInfo;public event EventHandler <CarInfoEventArgs> NewCarInfo{add{newCarInfo += value;}remove{newCarInfo = value;}}
Event Publisher contBefore firing the event, it is necessary to check whether the delegate NewCarInfo is not null . If no onesubscribed, the delegate is null :public void NewCar(string car){Console.WriteLine("CarDealer, new car {0}", car);if (NewCarInfo != null){NewCarInfo(this, new CarInfoEventArgs(car));}}
Event listenerEventsSample/Consumer.csEventsSample/Program.cs
Weak eventsWeakEventsSample/WeakCarInfoEventManager.cs
Event ListnerWeakEventsSample/Consumer.csWeakEventsSample/Program.cs
Thanks For Attending
Abed El-Azeem Bukhari (MCPD,MCTS and MCP)
el-bukhari.com