A delegate in C# is similar to a function pointer in C++. This allows encapsulating a reference to a method inside a delegate object.
A delegate is a type that defines a method signature. When you instantiate a delegate, you can associate its instance with any method with a compatible signature. You can invoke (or call) the method through the delegate instance.
An interesting and useful property of a delegate is that it does not know or care about the class of the object that it references
Delegates are especially used for implementing events and the call-back methods.
1. Basic delegate example
// declaration
MessageBox.Show("StartTestDelegate");
}
private void StopTestDelegate()
{
MessageBox.Show("StopTestDelegate");
}
// Instantiation
TestDelegate del1 = new TestDelegate(StartTestDelegate);TestDelegate del2 = new TestDelegate(StopTestDelegate);
// Invocation
del1();del2();
2. Math Operator delegate example
private class Math
{public int Add(int x, int y)
{
return x + y;
}
public int Sub(int x, int y)
{
return x - y;
}
public MathDelegate Operator(int op)
{
MathDelegate objDelegateMath = null; // delegate reference
if (op == 1)
objDelegateMath = Add; // point the reference to methods
else
objDelegateMath = Sub; // point the reference to methods
return objDelegateMath;
}
}
Math objMath = new Math();
//Invoke the methods through delegateMessageBox.Show(objMath.Operator(1).Invoke(1, 2).ToString());
MessageBox.Show(objMath.Operator(2).Invoke(5, 4).ToString());
3. Logger class delegate example
Multicast delegates >>