22
Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com

Csharp4 delegates lambda_and_events

Embed Size (px)

Citation preview

Page 1: Csharp4 delegates lambda_and_events

Abed El-Azeem Bukhari (MCPD,MCTS and MCP)el-bukhari.com

Page 2: Csharp4 delegates lambda_and_events

Delegates, Lambdas, and Events

Prepared By : Abed ElAzeem Bukhari

What ‘s in this chapter? ➤ Delegates ➤ Lambda expressions ➤ Events

Page 3: Csharp4 delegates lambda_and_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());}

Page 4: Csharp4 delegates lambda_and_events

Delegates cont.SimpleDelegate/MathOperations.csSimpleDelegate/Program.cs

Page 5: Csharp4 delegates lambda_and_events

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);}

Page 6: Csharp4 delegates lambda_and_events

BubbleSorter exampleBubbleSorter/BubbleSorter.csBubbleSorter/Employee.cs

Page 7: Csharp4 delegates lambda_and_events

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

Page 8: Csharp4 delegates lambda_and_events

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.

Page 9: Csharp4 delegates lambda_and_events

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"); }}}

Page 10: Csharp4 delegates lambda_and_events

Anonymous methodsAnonymousMethods/Program.cs

Page 11: Csharp4 delegates lambda_and_events

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

Page 12: Csharp4 delegates lambda_and_events

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));

Page 13: Csharp4 delegates lambda_and_events

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

Page 14: Csharp4 delegates lambda_and_events

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;}}

Page 15: Csharp4 delegates lambda_and_events

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”

Page 16: Csharp4 delegates lambda_and_events

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.

Page 17: Csharp4 delegates lambda_and_events

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

Page 18: Csharp4 delegates lambda_and_events

Event Publisher contprivate delegate EventHandler <CarInfoEventArgs> newCarInfo;public event EventHandler <CarInfoEventArgs> NewCarInfo{add{newCarInfo += value;}remove{newCarInfo = value;}}

Page 19: Csharp4 delegates lambda_and_events

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));}}

Page 20: Csharp4 delegates lambda_and_events

Event listenerEventsSample/Consumer.csEventsSample/Program.cs

Page 21: Csharp4 delegates lambda_and_events

Weak eventsWeakEventsSample/WeakCarInfoEventManager.cs

Event ListnerWeakEventsSample/Consumer.csWeakEventsSample/Program.cs

Page 22: Csharp4 delegates lambda_and_events

Thanks For Attending

Abed El-Azeem Bukhari (MCPD,MCTS and MCP)

el-bukhari.com