Ticker

6/recent/ticker-posts

Events in C#

Events in C#

C#, events are a way to implement the publish-subscribe pattern, where an object (publisher) notifies other objects (subscribers) when a specific action or state change occurs. Events provide a mechanism for loosely coupling components, allowing them to communicate without direct dependencies.

To define an event in C#, you need to declare a delegate type that specifies the signature of the event handlers, and then create an event based on that delegate. Here's an example that demonstrates the usage of events:

c#

using System;
// Declare a delegate type for the event handlers public delegate void EventHandlerDelegate(string message); // Publisher class public class Publisher { // Declare an event based on the delegate type public event EventHandlerDelegate OnEventOccurred; public void DoSomething() { // Perform some operation // Raise the event OnEventOccurred?.Invoke("Event occurred!"); } } // Subscriber class public class Subscriber { public void HandleEvent(string message) { // Event handler code Console.WriteLine("Event handled: " + message); } } // Main program public class Program { public static void Main() { Publisher publisher = new Publisher(); Subscriber subscriber = new Subscriber(); // Subscribe to the event publisher.OnEventOccurred += subscriber.HandleEvent; // Trigger the event publisher.DoSomething(); } }

In the example above, we have a Publisher class that declares an event called OnEventOccurred. The event is based on the EventHandlerDelegate delegate type, which specifies the signature of the event handlers.

The Publisher class has a method DoSomething() which performs some operation and then raises the event by invoking the OnEventOccurred event. The ?. null conditional operator is used to ensure that the event is only invoked if there are subscribers.

The Subscriber class defines a method HandleEvent() that matches the signature of the event handler delegate. This method represents the code that will be executed when the event occurs.

In the Main() method of the program, we create instances of the Publisher and Subscriber classes. We then subscribe the HandleEvent() method of the Subscriber object to the OnEventOccurred event of the object using the += operator.

Finally, we call the DoSomething() method of the Publisher object, which triggers the event. As a result, the event handler method HandleEvent() of the Subscriber object is invoked, and the message "Event handled: Event occurred!" is printed to the console.

Events allow objects to communicate in a loosely coupled manner. Publishers don't need to know anything about the subscribers, and subscribers can dynamically subscribe or unsubscribe from events based on their requirements. This decoupling improves code flexibility.

Post a Comment

0 Comments