This document discusses delegates, anonymous methods, lambda expressions, and events in C#. Delegates allow encapsulating references to methods and functions. Anonymous methods provide a way to pass code blocks as delegates without needing separate methods. Lambda expressions create anonymous functions using the => operator. Events enable classes to notify other classes when something of interest occurs, with publishers raising events and subscribers handling them.
Delegates, Lambdas
and Events
Delegates
Anonymous Methods
Lambda Expressions
Events
2.
Delegate
A delegatein 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
Defininga 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.
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<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.
Anonymous Methods
Creatinganonymous 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
Alambda 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 enablea 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.
The publisherdetermines 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{//…………}
}