- C# Events Introduction
- C# Events Example
- C# Events Example Part 2
- C# Events Example Part 3
- C# Events Example Part 4
This post directly continues on from our previous post called C# Events Example. Here we will add another subscriber and call it SubscriberTwo. It is a new class.
We need to modify code in our Program.cs file. We only need two new lines of code. We need to instantiate our new SubscriberTwo. Next we need to add a pointer. So to add more subscribers we do not need to modify any code in our publisher. Our publisher is the class ItemProcessor. Notice that all we do is add a new subscriber, SubscriberTwo and add that subscriber to our Main() program. With events, you can create a publisher and then you can add as many subscribers as you need without modifying any of the code in the publisher.
Here below is the code of our new subscriber.
using System; namespace EventsExample { class SubscriberTwo { public void OnItemProcessed(object source, EventArgs e) { Console.WriteLine("SubscriberTwo: doing something else..."); // maybe send SMS } } }
Below is the code we now have in our Program.cs after adding the two lines of code.
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 var subscriberTwo = new SubscriberTwo(); // subscriber Console.WriteLine("Beginning program EventsExample..."); // itemProcessed is a list of pointers to methods itemProcessor.ItemProcessed += subscriberOne.OnItemProcessed; itemProcessor.ItemProcessed += subscriberTwo.OnItemProcessed; itemProcessor.ProcessItem(item); } } }
Below is what our code produces as shown in a screenshot.