Presentation is loading. Please wait.

Presentation is loading. Please wait.

V 1.0 OE-NIK HP 1 Advanced Programming Delegates, Events.

Similar presentations


Presentation on theme: "V 1.0 OE-NIK HP 1 Advanced Programming Delegates, Events."— Presentation transcript:

1 V 1.0 OE-NIK HP 1 Advanced Programming Delegates, Events

2 V 1.0 OE-NIK HP 2 Using this type, we can declare variables that can store method references –The definition of the delegate type determines the signature of the methods it can store –With a matching method, the delegate variable can store it –The variable has null value if it is empty Delegate delegate double MyDelegate(int param1, string param2); double funct(int elso, string masodik) { return elso + masodik.Length; } MyDelegate del = new MyDelegate(funct); //hosszú megadás MyDelegate del = funct; //rövid megadás

3 V 1.0 OE-NIK HP 3 The C# language only supports multicast delegates, it is possible to store multiple methods in one variable: To call the methods inside a delegate variable: –The calling order is not guaranteed by the framework! (.NET 4.5: FIFO order) –When using a return value, the last method’s return value is obtained (almost NEVER used, see: GetInvocationList()) Usage of delegates del += new MyDelegate(Function1); //long syntax del += Function1; //short syntax del -= new MyDelegate(Function1); //long syntax del -= Function1; //short syntax MyDelegate temp = del; //Temporary variable if (temp != null) //Due to thread safety temp(0, "alma"); //

4 V 1.0 OE-NIK HP 4 Self-made delegate: –„Can accept methods with int+string parameters and double return type –+covariance +contravariance –Not used this semester, we use strict delegate typing We rarely use self-made delegates, we use built-in generic types instead Self-made or built-in delegates delegate double MyDelegate(int param1, string param2); delegate void MyOtherDelegate(int param1); MyOtherDelegate myVar;  Func myVar; MyDelegate myVar;  Action myVar;

5 V 1.0 OE-NIK HP 5 Built-in delegate types Predicate bool(T) List.Find(),.Exists(), RemoveAll()… Comparison int(T1,T2) List.Sort(), Array.Sort() MethodInvokervoid() EventHandlervoid(object,EventArgs) EventHandler void(object,T) (T EventArgs utód) Actionvoid() Action void(T) Action void(T1,T2) Action void(T1,T2,...,T16) Func TRes() Func TRes(T) Func TRes(T1,T2) Func TRes(T1,T2,...,T16)

6 V 1.0 OE-NIK HP 6 Lots of built-in usages in the framework! Using delegates in examples private bool IsEven(int i) { return i % 2 == 0; } private int EvensToFront(int i1, int i2) { bool i1Even = IsEven(i1); bool i2Even = IsEven(i2); if (i1Even && !i2Even) return -1; else if (!i1Even && i2Even) return 1; else return 0; } int[] arr; List list; //... int firstEven = list.Find(IsEven); List allEven = list.FindAll(IsEven); bool areThereAnyEven = list.Exists(IsEven); Array.Sort(arr, EvensToFront);

7 V 1.0 OE-NIK HP 7 delegate bool MyComparer(object left, object right); class SimpleExchangeSort { public static void Sort(object[] arr, MyComparer greater) { for (int i = 0; i < arr.Length; i++) for (int j = i + 1; j < arr.Length; j++) if (greater(arr[j], arr[i])) { object temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } Array.Sort-like example

8 V 1.0 OE-NIK HP 8 Array.Sort-like example class Student { public string Name { get; set; } public int Credits { get; set; } public Student(string name, int credits) { this.Name = name; this.Credits = credits; } Student[] group = new Student[] { new Student("Első Egon", 52), new Student("Második Miksa", 97), new Student("Harmadik Huba", 10), new Student("Negyedik Néró", 89), new Student("Ötödik Ödön", 69) };

9 V 1.0 OE-NIK HP 9 Array.Sort-like example bool CreditComparer(object first, object second) { return ((first as student).Credits < (second as student).Credits); } MyComparer del = new MyComparer(CreditComparer); SimpleExchangeSort.Sort(group, del); **OR** SimpleExchangeSort.Sort(group, CreditComparer);

10 V 1.0 Event vs. delegate We can specify a delegate-typed member variable in a class: DelegateType variableName; An event is similar, with an extra keyword: event DelegateType eventName;  The extra keyword provides additional security The event is usually public However, a public delegate gives no limitation OE-NIK HP 10 DelegateEvent Can be called from anywhereCan be called only from within the containing class Can be overwritten using assignment (=)The = operator is not allowed, only the += and -= operators can be used The usual property can be created with get and set keywords Special property with add (+=) and remove (-=) keywords Cannot be used in an interfaceCan be used in an interface

11 V 1.0 OE-NIK HP 11 Event handlint – naming conventions TaskNameLocation Event argument class...EventArgs (PropertyChangedEventArgs) In the namespace or in the event’s class Delegate...EventHandler (PropertyChangedEventHandler) In the namespace or in the event’s class Event... (PropertyChanged) In the event’s class Method designed to raise the event On... (OnPropertyChanged) In the event’s class Handling the event---In the event handler class

12 V 1.0 Nameless (anonymous) methods Usage of delegates: –Events –Methods as parameters Problem: the one-liner, single-use methods make the code “dirty” Solution: anonymous methods According to http://msdn.microsoft.com/en- us/library/bb882516.aspx OE-NIK HP 12 anonymous methods Anonymous functions lambda expressions

13 V 1.0 Anonymous methods Not really used any more (-> lambda expressions) OE-NIK HP 13 int firstEven = list.Find(delegate(int i) { return i % 2 == 0; }); List allEvenNumbers = list.FindAll(delegate(int i) { return i % 2 == 0; }); bool areThereAnyEvenNumbers = list.Exists(delegate(int i) { return i % 2 == 0; }); Array.Sort(arr, delegate(int i1, int i2) { bool i1Even = IsEven(i1); bool i2Even = IsEven(i2); if (i1Even && !i2Even) return -1; else if (!i1Even && i2Even) return 1; else return 0; });

14 V 1.0 Lambda expressions New operator: => (Lambda operator) –Used to connect the input and the output Syntax: parameter[s] => expression to define the output Usage: –We need a delegate type (self-made or built-in) –We create a variable, put a method inside using a lambda expression, then call the delegate: –The delegate defines the type of the input/output! OE-NIK HP 14 delegate double SingleParamMathOp(double x); SingleParamMathOp myOperation = x => x * x; double j = myOperation(5);

15 V 1.015 Lambda expressions Using a built-in delegate type: If there are more than one parameters, parentheses are necessary The typing of the parameters are not required, only in special (overloaded) cases delegate double TwoParamMathOp(double x, double y); TwoParamMathOp myFunc = (x, y) => x + y; double j = myFunc(5, 10); //j = 15 Func myFunc = (x) => x * x; int j = myFunc(5); //j = 25 Func myFunc2 = (x, y) => x + y; int j2 = myFunc2(5, 10); //j = 15

16 V 1.0 Lambda expressions OE-NIK HP 16 int firstEven = list.Find(i => i % 2 == 0); List allEvenNumbers = list.FindAll(i => i % 2 == 0); bool areThereAnyEvenNumbers = list.Exists(i => i % 2 == 0); Array.Sort(arr, (i1, i2) => { bool i1Even = IsEven(i1); bool i2Even = IsEven(i2); if (i1Even && !i2Even) return -1; else if (!i1Even && i2Even) return 1; else return 0; });

17 V 1.0 Lambda expressions Subtypes: –Expression Lambda Must be one expression, without curly braces x => x * x Will be compiled into an expression tree  optimizable! Also, it can be transformed/merged Typically used with IQueryable / databases –Statement Lambda Can be any complex code, with curly braces Every C# code structure is allowed x => { Console.WriteLine(x); } Will be compiled into a.NET delegate code OE-NIK HP 17

18 V 1.0 OE-NIK HP 18 Lambda expressions / anonymous methods Advantage: –The method is instantly readable at its usage location –Less “dirty” one-liner / single-use methods in the class Must only be used with short and single-use methods –Long code is harder to read –Since “embedded” into its usage location, it is not re-usable Do NOT use anonymous expressions within anonymous expressions! Must be careful with the Outer Variable Trap

19 V 1.0 Outer Variable Trap We can use the external variables from within anonymous methods and lambda expressions BUT these external variables are passed to the anonymous methods as a reference - the value types AS WELL! „Expected” output: 0, 1, 2, 3, 4, 5, … Actual output: 10, 10, 10, 10, 10 … Solution: we have to use a temporary variable that will never change its value OE-NIK HP 19 Action numberWriter = null; for (int i = 0; i < 10; i++) { numberWriter += delegate() { Console.WriteLine(i); }; } numberWriter(); //... int f = i; numberWriter += delegate() { Console.WriteLine(f); }; //...

20 V 1.0 Exercise Let’s create an all-purpose Logger class that can use any arbitrary logging modes. The signature for a logging method is: void(string message) Add two public methods: AddLogMethod(), Log() Test the class with at least two different logging modes (e.g.: file output, console output) Implement a third logging mode: log to an internal list Implement a Filter method for the internal list! OE-NIK HP 20

21 V 1.0 OE-NIK HP 21 Sources Events tutorial: http://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx Event modifier: http://msdn.microsoft.com/en-us/library/8627sbea(vs.71).aspxhttp://msdn.microsoft.com/en-us/library/8627sbea(vs.71).aspx Anonymous methods: http://msdn.microsoft.com/en-us/library/bb882516.aspx Anonymous methods: http://msdn.microsoft.com/en-us/magazine/cc163970.aspx Anonymous methods: http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx Anonymous methods: http://www.csharp-station.com/Tutorials/Lesson21.aspx Anonymous methods: http://stackoverflow.com/questions/1116678/c-delegate-definition- anonymous-methods-vs-formally-defined-methodshttp://stackoverflow.com/questions/1116678/c-delegate-definition- anonymous-methods-vs-formally-defined-methods Delegate, Anonymous, Event: Reiter István: C# jegyzet (http://devportal.hu/content/CSharpjegyzet.aspx), 164-172. oldal

22 V 1.0 OE-NIK HP 22

23 23 OE-NIK HP


Download ppt "V 1.0 OE-NIK HP 1 Advanced Programming Delegates, Events."

Similar presentations


Ads by Google