What is an Event in C#?

πŸ’‘ Concept: Event

An event in C# is a message or signal that something has occurred, typically used to implement the publisher-subscriber model. It is declared using the event keyword and is based on delegates.

πŸ“˜ Quick Intro

Events allow objects to communicate in a loosely-coupled way. A class can raise an event to signal something has happened, and other classes can subscribe to be notified when that event occurs.

🧠 Analogy

Imagine a doorbell system: when someone presses the button (event trigger), it rings the bell (event handler responds). The button doesn’t need to know who hears the bellβ€”it just triggers the event.

πŸ”§ Technical Explanation

  • βœ… Events are based on delegates and can be subscribed to by multiple handlers.
  • πŸ“Œ Declared using the event keyword.
  • πŸ” Events ensure encapsulation by restricting direct invocation from outside the class.
  • πŸ”„ Supports multicast (multiple subscribers).
  • πŸ”” Widely used in GUI, async programming, and observer patterns.

🎯 Use Cases

  • βœ… User interface programming (e.g., button click).
  • βœ… Logging and monitoring system activities.
  • βœ… Broadcasting updates to multiple subscribers (observer pattern).
  • βœ… Triggering chained business logic actions.

πŸ’» Code Example

public class Alarm {
    public delegate void AlarmEventHandler(string message);
    public event AlarmEventHandler OnAlarm;

    public void Trigger() {
        OnAlarm?.Invoke(""Alarm has been triggered!"");
    }
}

class Program {
    static void Main() {
        Alarm alarm = new Alarm();
        alarm.OnAlarm += (msg) => Console.WriteLine(""Handler 1: "" + msg);
        alarm.OnAlarm += (msg) => Console.WriteLine(""Handler 2: "" + msg);
        alarm.Trigger();
    }
}

❓ Interview Q&A

Q1: What is an event in C#?
A: It’s a way for a class to notify other classes that something has occurred.

Q2: How are events different from delegates?
A: Events are based on delegates but add encapsulation and prevent direct invocation.

Q3: Can an event have multiple subscribers?
A: Yes, it supports multicast.

Q4: What is the syntax to declare an event?
A: Use the event keyword with a delegate type.

Q5: What happens if no handler is attached to an event?
A: Nothing happens; the event simply doesn't invoke.

Q6: Where are events commonly used?
A: In GUI applications, async systems, and real-time monitoring.

Q7: Can events return values?
A: No, events do not return values directly.

Q8: Can you remove an event handler?
A: Yes, using -= syntax.

Q9: Can an event be triggered from outside the class?
A: No, only from within the class it is declared.

Q10: What is the purpose of ?.Invoke()?
A: It safely checks if any subscribers exist before invoking the event.

πŸ“ MCQs

Q1. What keyword is used to declare an event in C#?

  • delegate
  • event
  • trigger
  • handler

Q2. What type of pattern do events follow?

  • Builder
  • Observer
  • Factory
  • Adapter

Q3. Can events be multicast?

  • No
  • Yes
  • Only with lambdas
  • Only in GUIs

Q4. Can events be invoked from outside the declaring class?

  • Yes
  • No
  • Only with static
  • If public

Q5. Which delegate syntax is required for events?

  • Only Func
  • Custom delegate or EventHandler
  • Only Action
  • None

Q6. What happens if you invoke an event with no subscribers?

  • Error
  • NullReference
  • Nothing
  • Auto-subscribe

Q7. What is used to unsubscribe from an event?

  • +=
  • -=
  • !
  • delete

Q8. Which keyword helps check null before invoking event?

  • !
  • ??
  • ?.
  • if

Q9. Are events the same as methods?

  • Yes
  • No
  • Sometimes
  • Only if static

Q10. What is a practical use of events?

  • Storing data
  • Running threads
  • Notifying UI changes
  • Compiling code

πŸ’‘ Bonus Insight

Events help build scalable and loosely coupled applications. By allowing classes to signal actions without knowing the listeners, events enable modular, testable architectures commonly seen in desktop, mobile, and web apps.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

πŸ” Navigation

πŸ’¬ Feedback
πŸš€ Start Learning
Share:

Tags: