C# event
In C#, an event is a mechanism that enables a class or object to notify other classes or objects when an action or state change occurs. Events are used to establish communication between objects or classes, making it possible to create loosely coupled systems that are more modular and maintainable.
An event consists of a delegate and an event handler. The delegate is a reference to a method that is called when the event occurs. The event handler is a method that is executed when the event is raised. The event handler method must have the same signature as the delegate.
In C#, events are declared using the event
keyword. Here is an example of how to declare and raise an event:
public class Example { // Declare an event using the event keyword. public event EventHandler MyEvent; public void DoSomething() { // Raise the event. MyEvent?.Invoke(this, EventArgs.Empty); } }Sow:ecruww.theitroad.com
In this example, the Example
class declares an event named MyEvent
of type EventHandler
. The DoSomething
method raises the event using the MyEvent
delegate. The ?.
operator is used to check if the delegate is null before invoking it to avoid a null reference exception.
To handle an event, you need to attach a method to the event. This is done using the +=
operator. Here is an example of how to handle the MyEvent
event:
public class EventHandlerClass { public void HandleEvent(object sender, EventArgs e) { Console.WriteLine("Event handled"); } } public class Program { static void Main(string[] args) { Example example = new Example(); EventHandlerClass eventHandler = new EventHandlerClass(); // Attach the HandleEvent method to the MyEvent event. example.MyEvent += eventHandler.HandleEvent; // Call the DoSomething method to raise the event. example.DoSomething(); // Output: "Event handled" } }
In this example, the EventHandlerClass
class defines a method named HandleEvent
that handles the MyEvent
event. The Main
method attaches the HandleEvent
method to the MyEvent
event using the +=
operator. When the DoSomething
method is called, it raises the MyEvent
event, which causes the HandleEvent
method to be executed. The output is "Event handled".