Possible Duplicate:
Difference between events and delegates and its respective applications
Hi,
I am kind of new here, I wanted to know what is the difference between Delegates & Event usages? How can I choose which one to use?
Thanks!
Possible Duplicate:
Difference between events and delegates and its respective applications
Hi,
I am kind of new here, I wanted to know what is the difference between Delegates & Event usages? How can I choose which one to use?
Thanks!
If you are writing a class that exposes events, there is a subtle difference between using the event keyword or not. For example the following code is valid and will allow clients to subscribe to either ExposedAsEvent or ExposedAsDelegate:
public delegate void ExposedEventHandler(object sender, EventArgs e);
public MyClass{
public event ExposedEventHandler ExposedAsEvent;
public ExposedEventHandler ExposedAsDelegate;
}
The only difference is that using the event modifier restricts what clients can do with the delegate. In this case clients cannot invoke the delegate directly or set it to null.
Remove the event prefix and the delegate can still be used similar to an event, however it can also be possibly 'misued' by clients.
The event modifier is really just a way of further clarifying the intent to clients of your class and limiting access (encapsulation).
Delegates are used for events in C#. A delegate is a signature for a method that can be called by an Event. An example would be:
public delegate void MessageHandler(string message);
an event that uses that delegate would be:
public event MessageHandler NewMessage;
to call the event:
NewMessage("Hello events");
which would call a method using the delegate above such as:
public void Client_NewMessage(string message)
{
MyTextBox.Text += message;
}
To subscribe to the event (using a local method implementing the delegate):
Client cl = new Client();
cl.NewMessage += new MessageHandler(Client_NewMessage);
From MSDN:
Event:
An event is a message sent by an object to signal the occurrence of an action
Delegate:
A delegate is a class that can hold a reference to a method
In respect to event handling, the question is not really whether to use the one or the other. The class defines an event which is executed when some action takes place, and the consumer assigns a method which matches the delegate definition of the event.