We use events and delegates
to extend applications and to implement loose coupling. Rather than adding
various method calls within an implementation and then recompiling the class,
we publish the need to call a set of methods as an event from the class that will invoke those methods (publisher).
The publisher will thus define the delegate
which will act as the contract/agreement between the publisher and the
subscriber (where the specific method is defined) and will define the method
signature as it is implemented in the subscriber.
There are 5 steps to achieve this:
In Publisher
Step 1 – Define the delegate which will act as the
contract/agreement between the publisher and the subscriber (where the specific
method is defined) and will define the method signature as it is implemented in
the subscriber.
Syntax à public
delegate void NameOfEventHandler(object source, EventArgs e);
The above delegate will hold a
reference to a method that looks like above
Step 2 – Define the event in publisher based on the delegate
Syntax à
public event NameOfEventHandler MessageEncrypted;
Step 3 – Raise / publish event
How to define and call the event handling method –
Call the method à
OnMessageEncrypted;
Define the method
protected virtual void OnMessageEncrypted(){
if(MessageEncrypted)
!= null
MessageEncrypted(this,
EventArgs.Empty);
}
In Subscriber
Step 4 – Define the subscriber method whose signature
matches that of delegate
public class MailService
{
public void OnMessageEncrypted(Object source, EventArgs e)
{
Console.WriteLine("Sending Mail
with encrypted message ");
}
}
Step 5 – Define event handler in calling program and call
the method in publisher
static void Main(string[] args)
{
var video = new Message {Title = "Confidential"};
var MessageEncrypter = new MessageEncrypter(); // publisher
var mailService = new MailService(); //subscriber
MessageEncrypter.MessageEncrypted += mailService.OnMessageEncrypted;
MessageEncrypter.Encrypt(message);
}
If you want to pass in argument values, modify the
delegate/event definition and the raise event methods as below –
public event EventHandler<MessageEventArgs> MessageEncrypted;
public void Encrypt(Message message)
{
Console.WriteLine("Encrypting Message");
Thread.Sleep(3000);
OnMessageEncrypted(message);
}
protected virtual void OnMessageEncrypted(Message message)
{
if (MessageEncrypted != null)
MessageEncrypted(this, new MessageEventArgs() { Message = message });
}
Define child class as needed derived from the EventArgs
class
public class MessageEventArgs : EventArgs
{
public Message Message { get; set; }
}
Modify the subscribers as
-
public void OnMessageEncrypted(object source, MessageEventArgs e)
{
Console.WriteLine("Sending Text >>>" + e.Message.Title);
}