Events and Delegates in C# are undoubtedly among the most confusing topics. Let us explore more about these. The code used in this article can be downloaded from GitHub.

Delegates

Delegates are function pointers. Let’s write some code using delegates to understand delegates.

I have created a sample console application. When a user registers, an email and SMS verification is sent.

  1. class Program {
  2. static void Main() {
  3. var registerUser = new RegisterUser();
  4. var emailVerification = new EmailVerification();
  5. var smsVerification = new SMSVerification();
  6. registerUser.registerUserDelegateInstance += emailVerification.OnUserRegistered;
  7. registerUser.registerUserDelegateInstance += smsVerification.OnUserRegistered;
  8. registerUser.RegisterAUser(); // Call delegate
  9. Console.ReadLine();
  10. }
  11. }
  12. public class RegisterUser {
  13. public delegate void registerUserDelegate(); // declare a delegate
  14. public registerUserDelegate registerUserDelegateInstance; // create a delegate instance
  15. public void RegisterAUser() {
  16. Console.WriteLine("User registered");
  17. if (registerUserDelegateInstance != null) {
  18. registerUserDelegateInstance(); // Call the delegate
  19. }
  20. }
  21. }
  22. public class EmailVerification {
  23. public void OnUserRegistered() {
  24. Console.WriteLine("Sent Email for Verification");
  25. }
  26. }
  27. public class SMSVerification {
  28. public void OnUserRegistered() {
  29. Console.WriteLine("Sent SMS for Verification");
  30. }
  31. }
In the above code, we have initially defined a delegate signature (registerUserDelegate). Any method that accepts no parameters and returns void can be pointed by this delegate, i.e., the method this delegate points to should have the same method signature (OnUserRegistered).

We have created a delegate instance ‘registerUserDelegateInstance‘ which points to OnUserRegistered methods of EmailVerification & SMSVerification classes. When a delegate instance is called in the RegisterAUser method, all the methods it points to are executed.

If we run the application, we get an output as below.

Events And Delegates In C#

Advantages of using Delegates

Disadvantages of using Delegates

You can make a delegate instance null as below.

  1. registerUser.registerUserDelegateInstance = null;
Events And Delegates In C#
Now, the output will be as below.
Events And Delegates In C#

The email verification and SMS verification methods are not called as the delegate becomes null.

Let’s have a look at how events help us solve this issue.

Events

Let’s have a look at how we can use events help provide delegate encapsulation.

I have modified the above code as below.

  1. class Program {
  2. static void Main() {
  3. var registerUser = new RegisterUser();
  4. var emailVerification = new EmailVerification();
  5. var smsVerification = new SMSVerification();
  6. registerUser.registerUserEvent += emailVerification.OnUserRegistered; //subscribe to an event
  7. registerUser.registerUserEvent += smsVerification.OnUserRegistered; //subscribe to an event
  8. registerUser.RegisterAUser(); // publisher
  9. Console.ReadLine();
  10. }
  11. }
  12. public class RegisterUser {
  13. public delegate void registerUserEventHandler(object source, EventArgs Args); //define a delegate
  14. public event registerUserEventHandler registerUserEvent; // define an event
  15. public void RegisterAUser() {
  16. Console.WriteLine("User registered");
  17. if (registerUserEvent != null) {
  18. registerUserEvent(this, EventArgs.Empty); // call event
  19. }
  20. }
  21. }
  22. public class EmailVerification {
  23. public void OnUserRegistered(object source, EventArgs e) {
  24. Console.WriteLine("Sent Email for Verification");
  25. }
  26. }
  27. public class SMSVerification {
  28. public void OnUserRegistered(object source, EventArgs e) {
  29. Console.WriteLine("Sent SMS for Verification");
  30. }
  31. }
I have a class ‘RegisterUser’. This class has delegate ‘registerUserEventHandler’. Then, I have created an event based on that delegate called ‘registerUserEvent’. When a user registers, the RegisterAUser method calls the event that we had declared earlier. So what is happening here is that when a user registers, it calls an event.

I have then created an EmailVerification which will contain a method ‘OnUserRegistered’ that will receive parameters sent by an event.

In our Main class, the EmailVerification & SMSVerification will subscribe to the event.

Let’s run the code.

The output is as below.

Events And Delegates In C#

So, the summarised steps are,

  1. Declare a delegate (registerUserEventHandler)
  2. Declare an event based on that delegate (registerUserEvent)
  3. Create an event (registerUserEvent(this, EventArgs.Empty);)
  4. Subscribe methods to that event(registerUser.registerUserEvent += emailVerification.OnUserRegistered;)
  5. Fire that event (RegisterAUser)

Every time you declare an event, you do not have to declare a delegate too. Dotnet provides an inbuilt delegate called EventHandler which can be used directly while calling an event as below.

  1. public event EventHandler registerUserEvent;
  2. class Program
  3. {
  4. static void Main()
  5. {
  6. var registerUser = new RegisterUser();
  7. var emailVerification = new EmailVerification();
  8. var smsVerification = new SMSVerification();
  9. registerUser.registerUserEvent += emailVerification.OnUserRegistered; //subscribe to an event
  10. registerUser.registerUserEvent += smsVerification.OnUserRegistered; //subscribe to an event
  11. registerUser.RegisterAUser(); // publisher
  12. Console.ReadLine();
  13. }
  14. }
  15. public class RegisterUser
  16. {
  17. public event EventHandler registerUserEvent;
  18. public void RegisterAUser()
  19. {
  20. Console.WriteLine("User registered");
  21. if (registerUserEvent != null)
  22. {
  23. registerUserEvent(this, EventArgs.Empty);// call event
  24. }
  25. }
  26. }
  27. public class EmailVerification
  28. {
  29. public void OnUserRegistered(object source, EventArgs e)
  30. {
  31. Console.WriteLine("Sent Email for Verification");
  32. }
  33. }
  34. public class SMSVerification
  35. {
  36. public void OnUserRegistered(object source, EventArgs e)
  37. {
  38. Console.WriteLine("Sent SMS for Verification");
  39. }
  40. }
But if we try to make the event null, it won’t let us.
Events And Delegates In C#

So, events are encapsulated delegates that provide an extra layer of security. This is the reason why we prefer using events over delegates.

I hope this article brings you one step closer to understanding events and delegates.

Here is a great video by Mosh to understand the same.

More articles,

This article was originally published on my website taagung.