C# Events
At this Event, Microsoft hopes to inform developers about the features of both new and old products. Microsoft will notify the developer of the Event, in this case, via Email or other advertising channels. Therefore, Microsoft will act as a publisher in this instance, raising the Event and informing the developers of it. Developers will handle the Event as a subscriber to the Event.
Similar principles apply to Events in C#. Various procedures, such as click and mouseover, can be carried out by a button. The Event that we will use to inform the other subscriber classes about upcoming events is contained in the custom class. As a result, we will define the Event in this instance and alert the other classes that it includes the event handler.
The Event is an encapsulated delegate. Events with delegates are supported by both C# and.NET. Delegates must be used to managing events since there is a close relationship between events and delegates in terms of dispatching them. While the class sending the Event is known as the publisher, the class handling the Event is referred to as a subscriber.
Key Points about the Events are:
The essential components of the significant events are as follows:
- In C#, the event handler takes two parameters and outputs void.
- The first argument of the Event is also known as the source that will publish the item.
- Several subscribers may be present for a single event.
- Typically, the Event is used for a single user action, such hitting a button.
- If the Event has many subscribers, the event handler is called synchronously.
Declaration of the Event
Steps for Implementing the Event
To define the Event in the class, the delegate's event type must first be specified.
Invokation of the Event
if (CellEvent != null) CellEvent(this, e);
Only within the class where the Event was declared are we able to call the Event.
Hooking up the Event
OurEventClass.OurEvent += new ChangedEventHandler(OurEventChanged);
Detach the Event
OurEventClass.OurEvent -= new ChangedEventHandler(OurEventChanged);
Delegates function as a function's pointer. It is a reference data type and contains the method's reference. System. The Delegate class was implicitly descended from the delegate class.
A delegate may be declared using the delegate keyword and the signature.
Syntax of Delegates:
<access modifier> delegate <return type><delegate_name>(<parameters>)
Example of Delegates:
public delegate void PrintWord(int value);
Any method that shares the same return type and specified parameters as PrintWord can be pointed at using the previously mentioned PrintWord delegate. Here, we'll look at a declaration and use of the PrintWord delegates.
The PrintWord delegates in the previously mentioned example accept an int-type parameter and return void. We assign the PrintNum name method and declare the PrintWord type method in the primary () method. The PrintWord delegate will now be called, which will then call the PrintNum function. If the PrintWord delegates variable is assigned to the PrintMoney method, the PrintMoney method will be invoked in the same manner.
As illustrated below, we can build the delegate object using the new operator and specifying the method's name.
PrintWord printDel = new PrintWord(PrintNum);
Delegates can be declared as shown below:
public delegate void someevent();
public organize Event
Event - Basic Conceptual Implementation:
CODE:
The code is as follows:
class Program
{
static void Main(string[] args)
{
Publisher publisher = new Publisher();
Subscriber subscriber = new Subscriber(publisher);
publisher.Add(new Product
{
ProductName = "Complan", Price = 20
});
publisher.Add(new Product
{
ProductName = "Horlics", Price = 120
});
publisher.Add(new Product
{
ProductName = "Boost", Price = 200
});
subscriber.UnSubscribeEvent();
Console.ReadKey();
}
}
OUTPUT:
The Output for the following program will be:
A New Product Added.
A New Product Added.
A New Product Added.
Passing data by extending EventArgs:
To transfer data in the second parameter of the event handler from the publisher to subscribers, you must define a class that derives from the EventArgs class and stores the data you need to pass in the class.
The program that follows demonstrates how to send information (Email and Phone) from the publisher (Order class) to the subscribers (Email and SMS classes).
How it works.
The OrderEventArgs class, which derives from the EventArgs class, should first be defined.
Next, define the Event using the OrderEventArgs type of EventHanlder:
public event EventHandler<OrderEventArgs> OnCreated;
Third, create a new instance of the OrderEventArgs class and raise an event:
OnCreated(this, new OrderEventArgs { Email = email, Phone = phone });
The OrderEventArgs object in this statement holds the Email and phone information.
Fourth, modify the signature of the Send() method to take advantage of the OrderEventArgs:
public static void Send(object sender, OrderEventArgs e)
The OrderEventArgs object in the Send() method provides access to the Email and phone number.
Events are used as a channel of communication between objects in object-oriented programming. They enable one object—the publisher—to alert other objects—the subscribers—when a particular action or state change occurs. The selected event handler code can then be executed by the subscribers to respond to the Event.
Declaration and Subscription:
Based on events in C# is delegates. A delegate type represents a pointer to a method with a specific signature. It would help if you created an event delegate that contains the signature of the methods that can handle the Event before you can declare an event. Subscribers must define the method signature specified by the delegate, and it serves as a contract for them.
Once defined, the event delegate can declare an event inside a class. The event keyword is customarily prefixed before the Event, which can be public or private. By attaching their event handler methods to the Event, subscribers can then subscribe to the Event.
Raising and Handling Events:
The publisher invokes the Event as if it were a delegate to raise it. This is commonly accomplished by including an event-triggering protected or protected virtual method in the publisher class. This method calls the event delegate and passes any necessary event arguments.
Subscribers take care of the Event by implementing event handler methods that adhere to the event delegate's signature. When the Event is raised, these methods are carried out. The same Event can have several subscribers attach it with their event handlers so that everyone can react when it happens.
Null Checking and Event Invocation:
To ensure it has subscribers, it is crucial to carry out a null check before triggering an event. This is commonly done by ensuring that the Event is not null before executing it using the null-conditional operator (?.).
Event Arguments:
Through event arguments, events can also provide subscribers with additional data. Event arguments are derived or custom classes derived from the introductory class EventArgs. These classes have fields or properties that can store the relevant event-related data.
The kind of event arguments an event delegate will utilize can be specified when it is declared. You can make a new instance of the event arguments class and provide it to the event invocation when raising the Event. To retrieve pertinent information about the Event, subscribers can then access the event arguments within their event handler methods.
Unsubscribing from Events:
Events allow subscribers to stop receiving notifications by unsubscribing. This is commonly accomplished by separating the event handler procedure from the Event using the -= operator. When events are no longer required, it's crucial to unsubscribe from them to prevent memory leaks and pointless event alerts.
Event Access Modifiers:
Depending on the intended level of encapsulation, events can have a variety of access modifiers, including internal, protected, private, and public. The access modifier depends on which classes can subscribe to and raise the Event.
Event Best Practices:
It's crucial to follow some of the few best practices while working with events to ensure clean and maintainable code:
- Use the event keyword to declare events whenever possible, as it offers more protection and encapsulation.
- Give your events and event handler functions meaningful names to make your code easier to read.
- Record the occurrences and how they are used to instruct subscribers on handling them.
- To prevent unauthorized event invocation outside the class, avoid making events publicly settable.
Example:
CODE:
The code is as follows:
public class Publisher
{
public event EventHandler MyEvent;
protected virtual void OnMyEvent(EventArgs e)
{
MyEvent?.Invoke(this, e);
}
public void DoSomething()
{
OnMyEvent(EventArgs.Empty);
}
}
public class Subscriber
{
public void HandleEvent(object sender, EventArgs e)
{
Console.WriteLine("Event handled by Subscriber");
}
}
public class Program
{
public static void Main()
{
Publisher publisher = new Publisher();
Subscriber subscriber = new Subscriber();
publisher.MyEvent += subscriber.HandleEvent;
publisher.DoSomething(); // Output: Event handled by Subscriber
}
}
OUTPUT:
The Output for the following program will be:
Event handled by Subscriber
In the above example, the Publisher class declares an event of type EventHandler with the name MyEvent. The event handler method HandleEvent is implemented by the Subscriber class. The event handler method is subscribed to the Event using the += operator, generating an instance of Publisher and Subscriber. The Event is raised, and the handler is carried out when DoSomething is invoked.
Conclusion:
In C#, events offer an effective publish-subscribe method for objects to communicate with one another. They provide loose coupling between components, enabling them to communicate while unaware of one another. Publishers can alert subscribers to specific actions or state changes by declaring and raising events, and subscribers can reply by implementing event handler methods.
Delegates, which specify the signature of the event handler methods, are the foundation of events. An event delegate specifies the method signature subscribers must follow when an event is declared. The += operator is then used by subscribers to connect their event handler functions to the Event.
C# events give objects a powerful mechanism to interact and respond to actions or state changes. They encourage modularity and extensibility in applications and enable loose connectivity between components. Your C# programs' functionality and flexibility can be improved by comprehending events and how to use them.
The publisher invokes the event delegate to raise an event, which causes it to occur and notifies all event handlers who subscribe to it. Before triggering the Event, running a null check is crucial to ensure subscribers are associated. Event arguments can be used to pass subscribers more information, providing essential details about the Event.
Subscribers manage events by providing event handler methods that match the delegate's signature. The event handler methods are executed when the Event is raised, enabling subscribers to react using their unique logic. When using events, it's best to follow some rules, such as giving them meaningful names, documenting how to use them, and guaranteeing thread safety when working with multi-threaded systems.
Unsubscribing from events is crucial to avoid memory leaks and pointless event alerts. You can improve the flexibility, extensibility, and maintainability of your C# programs by comprehending and successfully using events. Events offer a flexible and decoupled method to handle object communication, improving the organization and maintainability of your code.