Events

You can think of an event as a kind of method that gets executed in some circumstances and notifies handlers or delegates about that incident. For example, when you sign up for an email newsletter, you get emails from the website about the latest articles, blog posts, or news that are posted. These emails could be daily, weekly, monthly, yearly, or according to some other specified period of time that you have chosen. These emails are not sent by a human being manually, but by an automatic system/software. This automatic email sender can be developed using events. Now, you might think, why do I need an event for this, can't I send an email to the subscriber by a normal method? Yes, you can. However, suppose that in the near future, you also want to introduce a feature where you will be notified on the mobile app. You'd have to change the code and add the functionality for that. A few days after that, if you want to further extend your system and send an SMS to specific subscribers, you have to change the code again. Not only that, but the code you write to achieve this will be very strongly coupled if you write it using normal methods. You can solve these kinds of problem using event. You can also create different event handlers and assign those event handlers to an event so that, whenever that event gets fired, it will notify all the registered handlers that will perform their work. Let's now look at an example to make this a little clearer:

using System;

namespace EventsAndDelegates
{
public delegate void GetResult();

public class ResultPublishEvent
{
public event GetResult PublishResult;

public void PublishResultNow()
{
if (PublishResult != null)
{
Console.WriteLine("We are publishing the results now!");
Console.WriteLine("");
PublishResult();
}
}
}

public class EmailEventHandler
{
public void SendEmail()
{
Console.WriteLine("Results have been emailed successfully!");
}
}

public class Program
{
public static void Main(string[] args)
{
ResultPublishEvent e = new ResultPublishEvent();

EmailEventHandler email = new EmailEventHandler();

e.PublishResult += email.SendEmail;
e.PublishResultNow();

Console.ReadLine();
}
}
}

The output of the preceding code is as follows:

In the preceding code, we can see that, when the PublishResultNow() method gets called, it basically fires the  PublishResult event. Furthermore, the SendMail() method that did subscribe to the event gets executed and prints Results have been emailed successfully! on the console.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.148.145.2