Basic Event Handling in C#

To illustrate event handling, you will make a news service that notifies its subscribers when an event (new news) occurs. Subscribers can unsubscribe and subscribe at will.

The Delegate

The delegate lets the subscriber know what type method can be notified. Essentially, the news service says "In case of an event occurring, I'll notify any registered method so long as it has the same signature as the delegate" and the subscriber says, "Okay, register this method." The method could be in any class.

You will use the following classes:

  • NewsService: Notifies the subscribers when events (new news) occur.
  • Subscriber: Instances subscribe to the news service, indicating what method should be notified.
  • News: Instances of this class are the parameters passed from the news service to the registered method. Contrary to what most people seem to think, it does not have to inherit from EventAgs. Any parameters can be passed.
using System;

// The delegate indicates what types of methods can be notified of
// an event.
// The method(s) must have the same signature as the delegate.
public delegate void NewsDelegate(News news);

public class News
{
  public string news;
  public News(string news) {this.news=news;}
}

// This class notifies subscribers when the specified event occurs.
// In this case, the event is that newNews() is called.
public class NewsService
{
  // Must have the following format: public event delegateName
  // anyName
  public event NewsDelegate NewsEventSubscribers;

  public void newNews(string news)
  {
    Console.WriteLine("An event! New news.");
    // first check whether there are subscribers to this event
    if (NewsEventSubscribers !=null)
    {
      // This will send an instance of News to each subscriber of
      // local news
      NewsEventSubscribers(new News(news));
    }
  }
  public NewsService(){}
}

public class Subscriber
{
  public string name;
  NewsDelegate delNews;

  public void SubscribeNewsService(NewsService ns)
  {
    // Create a new NewsDelegate. Its parameter is the method to
    // notify when the event occurs. This method also may be in
    // another class, in which case the parameter is
    // InstanceOfSomeOtherClass.method.
    delNews=new NewsDelegate(WriteNews); 
    // Register the delegate with the NewsService
    ns.NewsEventSubscribers +=delNews;
    Console.WriteLine(name + " subscribed to news.");
  }

  public void UnsubscribeNewsService(NewsService ns)
  {
    // unsubscribing
    ns.NewsEventSubscribers -=delNews;
    Console.WriteLine(name + " unsubscribed to news.");
  }

  // This method must have the same signature as
  // the delegate NewsDelegate declared above.
  public void WriteNews(News e)
  {
    Console.WriteLine(name + " received news: " + e.news);
   }

  public Subscriber(string name) {this.name=name;}
}

class MakeNews
{
  static void Main(string[] args)
  {
    NewsService ns=new NewsService();
    Subscriber julie=new Subscriber("Julie");
    julie.SubscribeNewsService(ns);
    Subscriber matthew=new Subscriber("Matthew");
    matthew.SubscribeNewsService(ns);
    ns.newNews("More money for schools.");
    julie.UnsubscribeNewsService(ns);
    ns.newNews("New mayor.");
   }
}

The output:

Julie subscribed to news.
Matthew subscribed to news.
An event! New news.
Julie received news: More money for schools.
Matthew received news: More money for schools.
Julie unsubscribed to news.
An event! New news.
Matthew received news: New mayor.


Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • At present, the most commonly deployed parallel file system is Lustre, and its adoption is growing across the HPC industry. According to Intersect 360 Research, "Through its leadership and involvement with OpenSFS, Cray advocates for the development of features that drive efficient performance at scale." Moreover, with help from Cray and OpenSFS, Lustre is gaining greater adoption across broader commercial application categories. As data and I/O requirements grow in commercial markets, technology vendors -- …

  • The 2014 State of DevOps Report — based on a survey of 9,200+ people in IT operations, software development and technology management roles in 110 countries — reveals: Companies with high-performing IT organizations are twice as likely to exceed their profitability, market share and productivity goals. IT performance improves with DevOps maturity, and strongly correlates with well-known DevOps practices. Job satisfaction is the No. 1 predictor of performance against organizational …

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date