About
In this code snippet, we will take a look at event arguments in C#.
Event arguments allow you to pass data(from publisher to subscriber) with the event when it is triggered. To return data with an event you must make a class that inherits from the EventArgs class. In this new derived class you can add the properties you want to send. Then you return this EventArgs child class with the event.
See this post if you want to know more about events themselves.
Let’s have a look at the code below to see how to use event arguments.
Code:
using System; namespace EventArguments { class Program { static void Main(string[] args) { Switch sw = new Switch(); Light light = new Light(sw); //Toggle the switch. sw.lightSwitchToggle("on"); sw.lightSwitchToggle("off"); Console.ReadLine(); } } class Switch { //Make a delegate. public delegate void ToggleDelegate(object sender, SwitchEventArgs e); //An event is basically a restricted delegate. //Other classes can only subscribe or unsubscribe from the event and can't invoke or assign it like a delegate. public event ToggleDelegate toggleEvent; //When this method is called the event will be invoked. public void lightSwitchToggle(string text) { //Pass toggleEvent this specific Switch class instance and the SwitchEventArgs object containig the data that we want to send. toggleEvent(this, new SwitchEventArgs(text)); } } //Define the event arguments object that will carry our data from the "publisher" to the "subscriber". public class SwitchEventArgs : EventArgs //Inherit from EventArgs and make a custom event argument. { public SwitchEventArgs(string Text) { text = Text; } public string text { get; set; } } class Light { Switch sw; public Light(Switch SW) { //Give Light a reference to the instance of Switch. sw = SW; //Add/chain/subscribe a new method on the event. sw.toggleEvent += turnOnTheLight; } private void turnOnTheLight(object sender, SwitchEventArgs e) { Console.WriteLine("The light was turned " + e.text + "."); } } }