Event-driven .NET: How to add an event to a class

In the previous article we saw how events work. In this article I’ll show how to add an event to a class. In order to illustrate this I’ve created a simple chat app that uses an in-memory message queue. Each chat window is subscribed to the message queue’s OnMessageReceived event, and updates their UI upon receiving a message.

1 – Add a delegate type, add an event to a class, and fire the event

  1. Declare the delegate type the delegate type is declared on its own – it’s not part of a class.
  2. Add the event – use the delegate type you just created
  3. Fire the event – The event will be null if there are no subscribers, so you always need to do a null check.
public delegate void MessageReceivedEventHandler(Message message); //1. declare the delegate type for the event

public class MessageQueue
{
	public event MessageReceivedEventHandler OnMessageReceived; //2. Add the event with the delegate type you declared 

	public void Enqueue(Message message)
	{
		OnMessageReceived?.Invoke(message); //3. fire the event
	}
}

2 – Subscribe to the event

There are two parts to subscribing to an event:

  • Subscribe using the syntax: event += method with the same signature as the delegate
  • Unsubscribe using the syntax: event -= method with the same signature as the delegate
public partial class frmChat : Form
{
	private readonly MessageQueue MessageQueue;
	private readonly Guid UserId;
	public frmChat(MessageQueue messageQueue)
	{
		InitializeComponent();

		UserId = Guid.NewGuid();

		this.MessageQueue = messageQueue;
		this.MessageQueue.OnMessageReceived += MessageQueue_OnMessageReceived; //1. subscribe
	}

	private void MessageQueue_OnMessageReceived(Message message)
	{
		txtChatWindow.AppendText($"{message.Time}\t{message.UserName}\t{message.Msg}\n");
	}

	private void btnSubmit_Click(object sender, EventArgs e)
	{
		MessageQueue.Enqueue(new Message(UserId, txtMessage.Text, txtName.Text));
	}

	private void frmChat_FormClosing(object sender, FormClosingEventArgs e)
	{
		MessageQueue.OnMessageReceived -= MessageQueue_OnMessageReceived; //2. unsubscribe
	}
}

Leave a Comment