Delegates anonymous functions and lambda expressions Delegates what
Delegates, anonymous functions and lambda expressions
Delegates, what is … • A type that defines a method signature • http: //msdn. microsoft. com/en-us/library/vstudio/ms 173171. aspx • Pointer to a function • Type safe • Example • Public delegate int Del(String text) • The name of this delegate id Del. • Instances of this delegate must be methods with one parameter of type String + return an int. • http: //msdn. microsoft. com/en-us/library/vstudio/ms 173171. aspx
The evolution of delegates • C# 1. 0 • Delegates must be assigned to a named method • C# 2. 0 • Delegates can be assigned to an anonymous method • Inline function • C# 3. 0 • Delegates can be assigned to a lambda expression • … a special kind of anonymous function • Example • http: //msdn. microsoft. com/en-us/library/vstudio/bb 882516. aspx • Lambdas. Etc: Cs. Version
Callback methods • A callback methods is a methods that is passed as a parameter to another method. • This other method can then call the callback method when needed. • Delegates are used for type safe callback methods • Example: • Lambdas. Etc -> Program. cs -> Some. Method. Using. Callbacks • Thread. With. Callback • Source • http: //en. wikipedia. org/wiki/Callback_%28 computer_science%29
Lambda expressions • Expression lambdas, general syntax • (input parameters) => expression • Examples • • () => some. Method(); // no parameters (x) => x * x; // one parameter (x, y) => x + y; // two parameters (int x, String str) => str. length == x; // typed parameters • Statement lambdas, • (input parameters) => { statements } • The statements usually has side-effects, like setting properties on objects or doing Console. write(…) • Lambdas are used in method-based LINQ queries as arguments to standard query operator methods such as WHERE • http: //msdn. microsoft. com/en-us/library/vstudio/bb 397687. aspx
References and further readings • MSDN • http: //msdn. microsoft. com/en-us/library/vstudio/bb 882516. aspx • MSDN • http: //msdn. microsoft. com/en-us/library/orm-9780596516109 -03 -09. aspx
- Slides: 6