In last post we discussed implementation of Delegates using one simple example. If you haven’t read it already i strongly encourage you to do so before moving to today’s topic. Today we will take closer look at events. In last example we created one main class with all methods inside it. Today we will learn how to communicate between different classes, by subscribing to the event.
Lets create our first class called publisher, here we will crate our event and we will publish it. This way we will be able to invoke methods in other classes.
using System; //We are using the delegates we described in last post public delegate void EventHandler(); class Program { //New event based on the delegate above called newEvent public static event EventHandler newEvent;
// Class constructor public Program(){ //You can put something here } public void AddSubscribers() { // Add event handlers to our event newEvent += new EventHandler(Command1); newEvent += new EventHandler(Command2); } static void Command1() { Console.WriteLine("Event executed"); } static void Command2() { Console.WriteLine("Warning!"); } public void InvokeEvent(){ //We are using this to invoke the event newEvent.Invoke(); } }
this is class of our program here we can subscribe new methods to our event and the most important, call our invoke method.
Now lets create second class so we can see how event behave with other classes.
Public class MainClass{ public static void Main(){ Program newProg= new Program(); //Now we can add our subscribers from Program class newProg.AddSubscribers(); //Or add subscriber from this class Subscribe(newProg); //Here we finally invoke our event newProg.InvokeEent() } //Here we can subscribe to event of different class public Subscribe(Program newProgram){ newProgram.newEvent += new EventHandler(Command3) } static void Command3() { Console.WriteLine("Great!"); } }
In this example we can see how we can use event to crate connections between different classes. We can use it in in many different cases, in games development we can crate event calling subscribers when unit is created or destroyed, this way we can easy handle methods spreader between all classes. In next entry I’ll cover lambda expressions, they can help you write more readable code faster. Stay Awesome!