C# Delegates

Click here to load reader

download C# Delegates

of 10

Transcript of C# Delegates

  • 1.Delegates, Lambdas and EventsDelegatesAnonymous MethodsLambda ExpressionsEvents

2. Delegate A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. 3. Declaring Delegate Defining a delegate means telling the compiler whatkind of method a delegate of that type will represents.Syntax for Delegate: delegate delgatename(params);Ex: public delegate int PerformCalculation(int x, int y); 4. Types of Delegates Single Cast Delegate A Single-cast derives from the System.Delegate class. It contains reference to one method only at a time. Multi Cast Delegate A multicast delegate derives from the System.MulticastDelegate class. It contains an invocation list of multiple methods. In multicasting a single delegate invokes multiple encapsulated methods. The return type of all these delegates is same. 5. Action and Func Delegates Action The generic Action delegate is meant to reference a method with void return. EX: Action (T1..T16 are input parameters) Func Func allows you to invoke methods with a return type. Ex: Func (T1,T2 etc are input parameters and Res is output parameter) 6. Anonymous Methods Creating anonymous methods is essentially a way to pass a code block as a delegate parameter. Ex: delegate void Del(int x); Del d = delegate(int k) { /* ... */ }; Using anonymous methods, reduce the coding overhead in instantiating delegates by eliminating the need to create a separate method. 7. Lambda Expressions A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types. All lambda expressions use the lambda operator =>, which is read as "goes to". Ex:delegate void TestDelegate(string s); TestDelegate myDel = n => { string s = n + " " + "World";Console.WriteLine(s); }; 8. Events Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers. 9. Pictorial Representation of Events 10. The publisher determines when an event is raised. The subscribers determine what action is taken in response to the event. Creating a Event: public event EventHandler Event-Name{ add{//} remove{//} }