Event-driven programming is a programming paradigm where the flow of the program is determined by events. An event is a change in the state of a program or an action that the program performs. In C#, event-driven programming can be implemented using delegates and events.
Here is an example implementation of event-driven programming in C#:
“`csharp
using System;
// Define a custom event arguments class
public class CustomEventArgs : EventArgs
{
public string Message { get; set; }
}
// Define a class that will emit events
public class EventEmittingClass
{
// Declare a delegate type
public delegate void CustomEventHandler(object sender, CustomEventArgs e);
// Declare an event based on the delegate type
public event CustomEventHandler CustomEvent;
// Method that will raise the custom event
public void RaiseEvent(string message)
{
// Create an instance of the event arguments class
var args = new CustomEventArgs { Message = message };
// Call the event handler (if any) and pass the event arguments
CustomEvent?.Invoke(this, args);
}
}
// Define a class that will handle the events
public class EventHandlerClass
{
// Event handler method for the custom event
public void HandleCustomEvent(object sender, CustomEventArgs e)
{
Console.WriteLine($”Event received: {e.Message}”);
}
}
public class Program
{
public static void Main(string[] args)
{
// Create an instance of the event emitter class
var emitter = new EventEmittingClass();
// Create an instance of the event handler class
var handler = new EventHandlerClass();
// Subscribe the event handler method to the custom event
emitter.CustomEvent += handler.HandleCustomEvent;
// Raise the custom event
emitter.RaiseEvent(“Hello, world!”);
}
}
“`
In this example, we define a custom event arguments class `CustomEventArgs` that inherits from `EventArgs`. We then define a class `EventEmittingClass` that contains a delegate type `CustomEventHandler` and an event `CustomEvent` based on the delegate type. The `RaiseEvent` method raises the event by invoking the event handler (if any) and passing the event arguments.
We also define a class `EventHandlerClass` that contains a method `HandleCustomEvent` to handle the custom event. In the `Main` method, we create an instance of the event emitter class `EventEmittingClass` and an instance of the event handler class `EventHandlerClass`. We then subscribe the event handler method to the custom event using the `+=` operator. Finally, we raise the custom event by calling the `RaiseEvent` method on the event emitter.
When the custom event is raised, the event handler method will be called and the message passed in the event arguments will be printed to the console.