Reader Level:
ARTICLE

Simple Delegates With Examples in C#

Posted by Mahesh Alle Articles | C# Language March 15, 2013
Here, you will see delegates with examples in C#.
  • 0
  • 0
  • 12664

Simple Delegates With Examples.

Delegates have the following properties:

  1. Delegates are similar to C++ function pointers, but are type safe.
  2. Delegates allow methods to be passed as parameters.
  3. Delegates can be used to define callback methods.
  4. Delegates can be chained together; for example, multiple methods can be called on a single event.
  5. Methods don't need to match the delegate signature exactly.
  6. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code that can call the referenced method, without having to know at compile time which method will be invoked.
  7. 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. 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.

Example1

Before applying the delegate:

protected void Page_Load(object sender, EventArgs e)
{

    if (!IsPostBack)
    {

        GetData("Mahesh");

    }

}

public
void GetData(string Name)
{

    lblName.Text = Name;

}

Output

Mahesh

After applying the delegate:  

public delegate void MyDelegare(string var);
protected
void Page_Load(object sender, EventArgs e)

{
    if (!IsPostBack)

    {

        MyDelegare objMyDelegare = new MyDelegare(GetData);

        objMyDelegare("Mahesh");

    }

}

public
void GetData(string Name)
{

    lblName.Text = Name;

}

Output

Mahesh

Multicast Delegate

It is a delegate that holds the reference of more than one method.

Multicast delegates must contain only methods that return void, else there is a run-time exception.

Example2

public delegate void MyDelegare(string var);
protected
void Page_Load(object sender, EventArgs e)
{

    if (!IsPostBack)
    {

        MyDelegare objMyDelegare = new MyDelegare(GetData);

        objMyDelegare += new MyDelegare(GetDat_one);

        //GetData and GetDat_one is called

        objMyDelegare("Mahesh");

        objMyDelegare -= new MyDelegare(GetDat_one);

        lblName.Text = lblName.Text + "<br />";

        //GetData is called

        objMyDelegare("Mahesh");

    }

}

public void GetData(string Name){
    lblName.Text = lblName.Text + "GetDate : " + Name;

}

public void GetDat_one(string Name)
{

    lblName.Text = lblName.Text + " GetDate_One : " + Name;

}

Output

GetDate : Mahesh GetDate_One : Mahesh
GetDate : Mahesh

COMMENT USING