Delgates are a special type of function used in C#.These are type safe.Delegates are refrence type that holds the address or reference to a method. By using delegate we can pass function as a parameter. C# delegates are similar to function pointer in C++.Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class.
Delegates can be chained together; for example, multiple methods can be called on a single event.
Here i declare a delegate which has void return type and takes 1 string type of parameter. Means we can pass reference of a method who takes the same return type and arguments like delegate.
Create object of Delegate
In this step i create delegate object by using new keyword and main thing to understand we have to pass method as a parameter at the time of delegate object creation.
Here is the close enough to understand delegate with a simple Example
Example:
Delegates can be chained together; for example, multiple methods can be called on a single event.
Basic syntax for delegate declaration
delegate <return type> <delegate-name> <parameter list>
Steps for working with delegate:
Declare delegate type
public delegate void printMessage(string str);
Here i declare a delegate which has void return type and takes 1 string type of parameter. Means we can pass reference of a method who takes the same return type and arguments like delegate.
Create object of Delegate
printMessage objDel=new printMessage(Your_Function_Name);
Call delegate
objDel("Your_Message");
public delegate void printMessage(string str);
protected void Page_Load(object sender, EventArgs e)
{
printMessage objDel=new printMessage(MyMessage);
objDel("Delegate
Successfully Called ");
}
public void MyMessage(string Message)
{
lblMessage.Text = Message
}
Multicast Delegate
A Multicast Delegate holds the reference of more than one method. But we can only call those methods who having the same return type like delgate otherwise there is a run-time exception.
We can add multiple methods in single delegate object using '+' operator and remove using '-' operator.Example:
protected void Page_Load(object sender, EventArgs e)
{
MyDelegate myDel = new MyDelegate(AddNumbers);
myDel += new MyDelegate(MultiplyNumbers);
myDel(10, 20);
}
public void AddNumbers(int x, int y)
{
int sum = x + y;
MessageBox.Show(sum.ToString());
}
public void MultiplyNumbers(int x, int y)
{
int mul = x * y;
MessageBox.Show(mul.ToString());
}
0 comments:
Post a Comment