C# Events Example


This entry is part 2 of 5 in the series C# Events

This post continues on from our previous post called C# Events which discussed what an event is. Here we use an example and illustrate some code. In this example we are using “general” names that are not too descriptive so that we can focus on the structure of the code and not what the code is specifically going to do. When we write events we will change the names of our classes to be more descriptive.

In the next post we will add another subscriber.

In our program we have four parts:

  1. Program.cs
  2. Item.cs
  3. ItemProcessor.cs
  4. SubscriberOne.cs

Later we will add another subscriber called SubscriberTwo.cs. Below is our code for the Program.cs.

using System;
namespace EventsExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var item = new Item() { Name = "Item 1 name" };
            var itemProcessor = new ItemProcessor();  // publisher
            var subscriberOne = new SubscriberOne();  // subscriber

            Console.WriteLine("Beginning program EventsExample...");
            
            // itemProcessed is a list of pointers to methods
            itemProcessor.ItemProcessed += subscriberOne.OnItemProcessed;

            itemProcessor.ProcessItem(item);
        }
    }
}

Below is our code for our item. It is very simple. It is just a class called Item with a single property.

namespace EventsExample
{
    public class Item
    {
        public string Name { get; set; }  // a property
    }
}

Below is our code for our publisher. This code raises the event. It is our publisher.

using System;
using System.Threading;
namespace EventsExample
{
    public class ItemProcessor
    {
        // 1. define a delegate (define signature)
        // 2. define an event based on that delegate (ItemProcessed in this case)
        // 3. raise the event
        public delegate void ItemProcessedEventHandler(object source, EventArgs args);
        public event ItemProcessedEventHandler ItemProcessed;

        public void ProcessItem(Item item)
        {
            Console.WriteLine("Processing Item...");
            Thread.Sleep(1500); // delay 1.5 seconds

            OnItemProcessed();
        }
        protected virtual void OnItemProcessed()
        {
            if (ItemProcessed != null)
                ItemProcessed(this, EventArgs.Empty);
        }
    }
}

Next is our code for our subscriber. Right now we only have one subscriber, but we can easily add another one later.

using System;
namespace EventsExample
{
    public class SubscriberOne
    {
        public void OnItemProcessed(object source, EventArgs e)
        {
            Console.WriteLine("SubscriberOne: doing something...");  // maybe send an email
        }
    }
}

Series Navigation<< C# Events IntroductionC# Events Example Part 2 >>