What is Delegates in C#? [Resolved]

Posted by Kamalakanta.Nayak09 under C# on 3/21/2012 | Points: 10 | Views : 2063 | Status : [Member] | Replies : 14
What is Delegates in C#? Can any body explain details?
Again What is diff between Event and Delegates?

Thanks,
K.K



Responses

Posted by: Madhurit on: 3/21/2012 [Member] Starter | Points: 50

Up
0
Down

Resolved
Delegates are similar to object references, but are used to reference methods instead of objects. The type of a delegate is the type or signature of the method rather than the class. Hence a delegate has three properties:

1. The type or signature of the method that the delegate can point to
2. The delegate reference which can be used to reference a method
3. The actual method referenced by the delegate

The Sample Program on the Delegates.


class Test
{
delegate int MyDelegate(int p, int q);
static int Add(int a, int b)
{
Return a+b;
}

static void Main()
{
MyDelegate arithMethod = new MyDelegate(Add);
int r = arithMethod(3, 4);
Console.WriteLine("The result of arithmetic operation `+' on 3 and 4 is: {0}", r);
}
}

The result of the above program will be


The result of arithmetic operation `+' on 3 and 4 is: 7

Events :
Events are certain actions that happen during the execution of a program that the application wishes to be notified about, so it can respond. An event can be a mouse click, a keystroke or the coming of a certain time (alarm). An event is basically a message which is said to be fired or triggered when the respective action occurs. A class that raises an event is called an 'event sender', a class that receives an event is called and 'event consumer' and a method which is used to handle a particular event is called an 'event handler'.

Event Handling in C#
1. Define a public delegate for the event outside any class boundary. The conventional signature of a delegate for an event is

public void EventDelegate(object sender, EventArgs e)

2.Define a class to generate or raise the event. Define a public event in the class using the event keyword and the public delegate:

public event EventDelegate MyEvent


3.Define a class to receive the events. This class is usually the main application class containing the Main() method Write an event handler method in the class. The signature of the event handler must be identical to that of the public delegate created in step 1. The name of the event handler method conventionally starts with the word "O"

public void OnMyEvent(object sender, EventArgs e)
{
// handle the event


}

Instantiate the event generator class created in step 2 like this:
EventClass eventObj = new EventClass();
Add the event handler written in the current class to the event generator class' event.
eventObj.MyEvent += new EventDelegate(OnMyEvent);

Now the event handler 'OnMyEvent()' will be called automatically whenever the event 'MyEvent' is triggered.

A Clock Timer Example
To help understand how events are implemented and received, let's look at the traditional "Clock Timer" example. The Clock Timer generates an event each second and notifies the interested clients through events. First we define a public delegate for the event, calling it 'TimerEvent':
public delegate void TimerEvent(object sender, EventArgs e);
Now we define a class named 'ClockTimer' to generate the event.
class ClockTimer
{
public event TimerEvent Timer;
public void Start()
{
for(int i=0; i<5; i++)
{
Timer(this, null);
Thread.Sleep(1000);

}
}
}

The class contains an event, 'Timer', of type TimerEvent delegate. In the Start() method, the event 'Timer' is raised each second for a total of 5 times. Here, we have used the Sleep() method of the System.Threading.Thread class, which takes the number of milliseconds the current thread will be suspended as its argument. We will explore threading and its issues in coming lessons. Next we need to define a class that will receive and consume the event, which is defined as:
class Test
{
static void Main()
{
ClockTimer clockTimer = new ClockTimer();
clockTimer.Timer += new TimerEvent(OnClockTick);
clockTimer.Start();

}
}

public static void OnClockTick(object sender, EventArgs e)
{
Console.WriteLine("Received a clock tick event!");

}

The class contains an event handler method, 'OnClockTick()', which follows the ClockEvent delegate's signature. In the Main() method of the class, we have created an instance of the event generator class 'ClockTimer'. Later we registered (or subscribed) the OnClockTick() event handler to the 'Timer' event of the ClockTimer class. Finally, we have called the Start() method, which will start the process of generating events in the ClockTimer class.

The complete source code of the program is shown below.

using System;
using System.Threading;




class ClockTimer

{
public event TimerEvent Timer;
public void Start()
{
for(int i=0; i<5; i++)
{
Timer(this, null);
Thread.Sleep(1000
}
}
public static void OnClockTick(object sender, EventArgs e)
{
Console.WriteLine("Received a clock tick event!");

}


}
class Test
{
public delegate void TimerEvent(object sender, EventArgs e);


static void Main()
{

ClockTimer clockTimer = new ClockTimer();
clockTimer.Timer += new TimerEvent(OnClockTick);
clockTimer.Start();

}
}

Note that we have also included the System.Threading namespace at the start of the program, as we are using its
Thread class in our code.
The output of the program is:

Received a clock tick event!
Received a clock tick event!

Received a clock tick event!
Received a clock tick event!
Received a clock tick event!

Thanks & Regrads,
T.Madhuri.

Kamalakanta.Nayak09, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sabarimahesh on: 3/21/2012 [Member] Bronze | Points: 25

Up
0
Down
Dlegate
A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method.


using System;


using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;



public partial class _Default : System.Web.UI.Page

{

public delegate void delFirst(int i);

public event delFirst evenFirts;



protected void Page_Load(object sender, EventArgs e)

{

Button bt = new Button();

bt.Attributes.Add("runat", "server");

bt.Text = "EVENT";



bt.Click += new EventHandler(eventTest);

form1.Controls.Add(bt);



delFirst delF;

delF = Add;

delF += sub;



evenFirts = delF;//new delFirst(Add);

//evenFirts += delF;//new delFirst(sub);



}

public void eventTest(object sender, EventArgs e)

{

Button bt1 = (Button)sender;

bt1.Text = "Clicked";

evenFirts(5);



}



public void Add(int i)

{

Label1.Text += "From Add :" + i;





}

public void sub(int i)

{

Label1.Text += "From Sub :" + i;

}



}


Life is a Race
Thanks & Regards
By
Sabari Mahesh P M

Kamalakanta.Nayak09, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sabarimahesh on: 3/21/2012 [Member] Bronze | Points: 25

Up
0
Down
Use This Code for learn Paractically

Life is a Race
Thanks & Regards
By
Sabari Mahesh P M

Kamalakanta.Nayak09, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Patel28rajendra on: 3/21/2012 [Member] Starter | Points: 25

Up
0
Down
Hi
refer this link

http://www.dotnetfunda.com/articles/article1311-method-delegate-using-moles.aspx

R D Patel

Kamalakanta.Nayak09, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sabarimahesh on: 3/22/2012 [Member] Bronze | Points: 25

Up
0
Down
Madhurit

Super


Life is a Race
Thanks & Regards
By
Sabari Mahesh P M

Kamalakanta.Nayak09, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Patel28rajendra on: 3/22/2012 [Member] Starter | Points: 25

Up
0
Down
Hi

T.Madhuri.

Nice Explanation

Thanks



R D Patel

Kamalakanta.Nayak09, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Akiii on: 3/24/2012 [Member] Bronze | Points: 25

Up
0
Down
Hello Madhuri, good explanation !
Keep it up...


Thanks and Regards
Akiii

Kamalakanta.Nayak09, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sabarimahesh on: 3/26/2012 [Member] Bronze | Points: 25

Up
0
Down
Sksamantaray
gOOd

Life is a Race
Thanks & Regards
By
Sabari Mahesh P M

Kamalakanta.Nayak09, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Patel28rajendra on: 3/26/2012 [Member] Starter | Points: 25

Up
0
Down
Hi

you can refer this linkl

http://msdn.microsoft.com/en-us/library/ms173171%28v=vs.80%29.aspx

R D Patel

Kamalakanta.Nayak09, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Patel28rajendra on: 3/26/2012 [Member] Starter | Points: 25

Up
0
Down
Hi

another nice link with Real Example

http://www.codeproject.com/Articles/71154/C-Delegates-101-A-Practical-Example

R D Patel

Kamalakanta.Nayak09, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sabarimahesh on: 3/27/2012 [Member] Bronze | Points: 25

Up
0
Down
Patel28rajendra

This is also Good

Life is a Race
Thanks & Regards
By
Sabari Mahesh P M

Kamalakanta.Nayak09, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Patel28rajendra on: 3/27/2012 [Member] Starter | Points: 25

Up
0
Down
Thanks



R D Patel

Kamalakanta.Nayak09, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sabarimahesh on: 3/27/2012 [Member] Bronze | Points: 25

Up
0
Down
Patel28rajendra
Welcome

Life is a Race
Thanks & Regards
By
Sabari Mahesh P M

Kamalakanta.Nayak09, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response