Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace World1
- {
- public delegate double MathAction(double num);
- public delegate void MyDelegate(string message);
- // public delegate void MyEventHandler(object sender, EventArgs arg);
- class DelegateTest
- {
- public double Double(double num)
- {
- return 2 * num;
- }
- public static void Test()
- {
- DelegateTest p = new DelegateTest();
- // 1. Named function
- MathAction d1 = p.Double;
- // MathAction d1 = new MathAction(Double);
- // Console.WriteLine(Calculate(Double, 3.14)); // this also works
- Console.WriteLine("The delegate says {0}", d1(3.14));
- // free variable. Used in the context of the anonymous function and lambdas
- // The functions can create closure.
- // Keeps information about the lexical scope where the function was defined.
- int freeVar = 3; // it is used in the functions bellow to create closure
- // 2. Anonymous function
- d1 = delegate(double num) {
- // return num * num; // no closure
- return num * num * freeVar; // closure - variable from the outer context is used
- };
- Console.WriteLine("The delegate says {0}", d1(3.14));
- // Lambda is a code snipped which can be passed as an argument of a function
- // or returned from a function as a return value
- // Usually anonymous functions are used as lambdas. They may or not create closure
- // 3. Lambda Expressions
- // d1 = (x, y) => { x++; return x * x * x; }; // statement. Has {...} and "return"
- // 3.1. lambda Expression
- // (The expression consists of operators literals, identifiers, evaluates to a value)
- d1 = x => x * x * x; // expression
- d1 = x => x * x * x * freeVar; // expression and creates closure
- (freeVar is used in the body but it is not declared in the body of the function)
- // 3.2. Lambda Statement
- d1 = x => {x++; return x * x * x}; // Lambda statement
- d1 = x => {x++; return x * x * x * freeVar}; // Lambda statement creates closure (freeVar is used)
- Console.WriteLine("The delegate says {0}", d1(3.14));
- // Console.WriteLine("Functional calculator {0}", p.Calculate(s => s * s, 2.71));
- // Console.WriteLine("Functional calculator {0}", p.Calculate(delegate(double num) { return num * num; }, 2.71));
- Console.WriteLine("Functional calculator {0}", p.Calculate(d1, 2.71));
- }
- public double Calculate(MathAction action, double num)
- {
- return action(num);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment