C# Interview Questions

36 Questions
C# Programming

C# Programming

Web DevelopmentFrontendBackendGame Dev

Question 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

  1. Publisher: The class that contains the event and raises it.
  2. Subscriber: The class that receives the notification when the event is raised.
  3. Delegate: Defines the signature of the event handler method that will be called when the event is raised.
  4. Event: A special delegate that is declared using the event keyword.

Declaring and Using Events

Declaration

  1. Delegate Declaration: First, declare a delegate that defines the signature for the event handler.
  2. 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 called Notify.
  • Subscriber has a method OnNotify that handles the event.
  • Program creates instances of Publisher and Subscriber, subscribes subscriber.OnNotify to publisher.Notify, raises the event, and finally unsubscribes the event.

Event Usage Scenarios

  1. User Interface Elements:
    • Button clicks, text input changes, and other UI interactions.
  2. System Notifications:
    • System events like file changes, network status updates, or timer ticks.
  3. 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.

  1. EventHandler Delegate:

    • Represents a method that will handle an event.
    • Has a standard signature: void EventHandler(object sender, EventArgs e).
  2. Custom EventArgs:

    • Inherit from EventArgs to pass custom data with an event.
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

  1. Decoupling:
    • Events provide a way to decouple the publisher and subscriber, promoting loose coupling.
  2. Flexibility:
    • Multiple subscribers can respond to the same event, and a subscriber can handle multiple events.
  3. 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.

Recent job openings