C# Interview Questions
C# Programming
Web DevelopmentFrontendBackendGame DevQuestion 12
What are events in C# and how are they used?
Answer:
Events in C# are a way for a class or object to provide notifications to other classes or objects when something of interest occurs. They are built on top of delegates and provide a mechanism for implementing the observer design pattern. Events enable a publisher-subscriber relationship where the publisher raises an event and the subscribers respond to it.
Key Concepts of Events
- Publisher: The class that contains the event and raises it.
- Subscriber: The class that receives the notification when the event is raised.
- Delegate: Defines the signature of the event handler method that will be called when the event is raised.
- Event: A special delegate that is declared using the
event
keyword.
Declaring and Using Events
Declaration
- Delegate Declaration: First, declare a delegate that defines the signature for the event handler.
- Event Declaration: Declare an event based on the delegate.
public class Publisher
{
// Declare a delegate
public delegate void NotifyEventHandler(string message);
// Declare an event of delegate type
public event NotifyEventHandler Notify;
// Method to raise the event
public void RaiseEvent(string message)
{
if (Notify != null)
{
Notify(message);
}
}
}
Subscription
A subscriber class needs to define a method matching the delegate signature and subscribe to the event.
public class Subscriber
{
// Event handler method
public void OnNotify(string message)
{
Console.WriteLine($"Received message: {message}");
}
}
public class Program
{
public static void Main()
{
// Create instances of publisher and subscriber
Publisher publisher = new Publisher();
Subscriber subscriber = new Subscriber();
// Subscribe to the event
publisher.Notify += subscriber.OnNotify;
// Raise the event
publisher.RaiseEvent("Hello, World!");
// Unsubscribe from the event
publisher.Notify -= subscriber.OnNotify;
}
}
In this example:
Publisher
raises an event calledNotify
.Subscriber
has a methodOnNotify
that handles the event.Program
creates instances ofPublisher
andSubscriber
, subscribessubscriber.OnNotify
topublisher.Notify
, raises the event, and finally unsubscribes the event.
Event Usage Scenarios
- User Interface Elements:
- Button clicks, text input changes, and other UI interactions.
- System Notifications:
- System events like file changes, network status updates, or timer ticks.
- Custom Events:
- Application-specific events such as completion of a task, data changes, or logging actions.
Advanced Event Handling
Using EventHandler
and EventArgs
C# provides a predefined delegate EventHandler
and a base class EventArgs
for event handling.
-
EventHandler Delegate:
- Represents a method that will handle an event.
- Has a standard signature:
void EventHandler(object sender, EventArgs e)
.
-
Custom EventArgs:
- Inherit from
EventArgs
to pass custom data with an event.
- Inherit from
public class CustomEventArgs : EventArgs
{
public string Message { get; }
public CustomEventArgs(string message)
{
Message = message;
}
}
public class Publisher
{
// Use EventHandler delegate with custom EventArgs
public event EventHandler<CustomEventArgs> Notify;
// Method to raise the event
public void RaiseEvent(string message)
{
if (Notify != null)
{
Notify(this, new CustomEventArgs(message));
}
}
}
public class Subscriber
{
// Event handler method
public void OnNotify(object sender, CustomEventArgs e)
{
Console.WriteLine($"Received message: {e.Message}");
}
}
public class Program
{
public static void Main()
{
Publisher publisher = new Publisher();
Subscriber subscriber = new Subscriber();
publisher.Notify += subscriber.OnNotify;
publisher.RaiseEvent("Hello, World!");
publisher.Notify -= subscriber.OnNotify;
}
}
Benefits of Events
- Decoupling:
- Events provide a way to decouple the publisher and subscriber, promoting loose coupling.
- Flexibility:
- Multiple subscribers can respond to the same event, and a subscriber can handle multiple events.
- Maintainability:
- Enhances code maintainability by separating the event-raising logic from the event-handling logic.
Summary
Events in C# provide a powerful mechanism for implementing the observer pattern, enabling one-to-many communication between objects. By using delegates and the event
keyword, developers can create flexible, decoupled systems where components can notify each other about important occurrences without tightly coupling their implementations.