Wednesday, December 19, 2012

Simple Delegate Example in .NET

.NET delegates are extensively used for notifications.
- Callbackes (eg: for asynchronous completion callbacks)
- Events (eg: OnClick event handler for buttons)

Delegates are like a function pointer in C/C++
- Define a delegate like declaring a function prototype.
- Create a variable whose type is a variable.
- Then point this variable at a real function and call the function through the delegate variable.

See below example.

Create a Calculator class with Add function.

public class Calculator
     public int Add(int operand1, int operand2)
          return operand1 + operand2;

In the web page add the below code.

public delegate int BinaryOperation(int Operand1, int Operand2);//Delegate definition
protected void Page_Load(object sender, EventArgs e)
 if (!Page.IsPostBack)
    Calculator calc = new Calculator();
    BinaryOperation adddel;// Declare a variable of delegate type
    adddel = calc.Add;//point the delegate variable at the add function
    Response.Write("1 + 2 = "+adddel(1,2));// call the function through delegate variable

You can assign any method to the delegate BinaryOperation that match the signature and method will be called each time delegate is called.

1 + 2 = 3

No comments:
Write comments
Recommended Posts × +