Saturday 7 November 2015

Delegate In C# With Example


Delegate is a type which  encapsulate a reference to a method inside a delegate object. Delegate are object-oriented, type-safe, and secure.

If this is our method :

public int add(int a, int b)
{
return a + b;
}




 To make reference to the method (add). 

 First we need to define the delegate to make its object (obvious).


Declaration :


Syntax

public delegate type_of_delegate delegate_name(  );

 It is declared globally i.e outside all functions.


public partial class Delegate : System.Web.UI.Page
{
public delegate int delegate_add(int a, int b);

protected void Page_Load(object sender, EventArgs e)
{
}



Using the delegate at a particular function, as said by passing the reference of the function(add) to the object of the delegate (AddUsingDelegate).


 protected void btnAdd_Click(object sender, EventArgs e)
{
delegate_add AddUsingDelegate = new delegate_add(add);
int result = AddUsingDelegate(int.Parse(txtNo1.Text), int.Parse(txtNo2.Text));

}


Putting Altogether 

public partial class Delegate : System.Web.UI.Page
{
public delegate int delegate_add(int a, int b);

protected void Page_Load(object sender, EventArgs e)
{
}

protected void btnAdd_Click(object sender, EventArgs e)
{
delegate_add AddUsingDelegate = new delegate_add(add);
int result = AddUsingDelegate(int.Parse(txtNo1.Text), int.Parse(txtNo2.Text));

}
public int add(int a, int b)
{
return a + b;
}
}


Advantages :


Encapsulating the method's call from caller
When we are using delegate it provide exact encapsulation as we are using a separate class. Here our method call is completely encapsulated


Effective use of delegate improves the performance of application
The performance is improved due to encapsulation and due to the fact that it is decided at run-time which method is called.

Anonymous" invocation
Property of a delegate is that it does not know or care about the class of the object that it references. Any object will do; all that matters is that the method's argument types and return type match the delegate's. This makes delegates perfectly suited for "anonymous" invocation.








No comments:

Post a Comment