- It’s used to represent or refer one or more functions
- Delegates are user defined types in C#.NET
- Delegates in C#.NET are similar to function pointers in C++
- It’s not a member of a class, but similar to a class
- To consume any delegate, we need to create an object to delegate
- A delegate is a type that references a method
- Once a delegate method can be invoked like any other method with parameters and written value
- These can be used to define callback methods
- These are the backbone for events
- These can be chained together, i.e. ,multiple methods can be called on a single event
Types of Delegates
There are of two types
of Delegates available
1) Single class
delegate 2) Multi cast delegate
- A delegate that represents only a single function is known as Single Cast Delegate
- A delegate that represents only a more than more than one functions is known as Multi Cast Delegate
- Delegates will support Generics
- In C#.NET 2.0 Version, a new feature of Delegate is introduced in Anonmous Delegate
- Delegate are obj.oriented, types are and secure
To Work With Delegate Use The Following Steps
- Creating a Delegate
- Instantiating a Delegate
- Invoking a Delegate
Ex:
If we consider a function, like…,
Public void Add
{
Code…
}
To refer this function,
if we want to use the delegate, we use the above steps like…
STEP 1: Creating A Delegate
Syntax: Access modifier
delegate return type Delegate name ([arguments list]);
Ex: public delegate
void Sample Delegate (int x, int y);
- When we create a delegate, Access modifier, return type , number of arguments and their data types of the delegate must and should be same as Access Modifier, return type, number of arguments and their data types of the function that we want to refer
STEP 2: Instantiating the Delegate
Syntax: Delegate name object name=new Delegate
name(Target function name);
Ex: SampleDelegate obj =new SampleDelegate(Add);
- At this step a reference will be maintained from the delegate object to the function that we want to refer
STEP 3:
Invoking the Delegate
Syntax:
Object Name([Arguments values])
Ex:
Obj(10,20)
- At this step the function that is referred by the delegate will be called for the execution
No comments:
Post a Comment