C# Delegates

2,394 views

Published on

Published in: Technology, News & Politics
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,394
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
152
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

C# Delegates

  1. 1. Delegates, Lambdas and EventsDelegatesAnonymous MethodsLambda ExpressionsEvents
  2. 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. 3. Declaring Delegate Defining a delegate means telling the compiler what kind of method a delegate of that type will represents. Syntax for Delegate:  <Access Specifier> delegate <returntype> delgatename(params); Ex:  public delegate int PerformCalculation(int x, int y);
  4. 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. 5. Action<T> and Func<T> Delegates Action<T>  The generic Action<T> delegate is meant to reference a method with void return.  EX:  Action<in T1, in T2 …. in T16> (T1..T16 are input parameters) Func<T>  Func<T> allows you to invoke methods with a return type.  Ex:  Func<in T1,in T2…,out Res> (T1,T2 etc are input parameters and Res is output parameter)
  6. 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. 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. 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. 9. Pictorial Representation of Events
  10. 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<ClassName> Event-Name { add{//………} remove{//…………} }

×