Why are events important in C# programming?
Think about how one part of a program can tell another part that something happened without knowing details.
Events let one object send a message to others when an action occurs, without the sender needing to know who is listening. This helps keep code flexible and easier to maintain.
What is the output of this C# code?
using System; class Publisher { public event Action OnChange; public void Raise() { OnChange?.Invoke(); } } class Program { static void Main() { Publisher p = new Publisher(); p.OnChange += () => Console.WriteLine("Event triggered"); p.Raise(); } }
Look at how the event is subscribed and then invoked.
The event OnChange is subscribed with a lambda that prints "Event triggered". When Raise() calls OnChange?.Invoke(), the message is printed.
What error will this code produce?
using System; class Publisher { public event Action OnChange; public void Raise() { OnChange(); } } class Program { static void Main() { Publisher p = new Publisher(); p.Raise(); } }
What happens if you call an event with no subscribers?
The event OnChange is null because no method subscribed. Calling OnChange() causes a NullReferenceException at runtime.
Which option shows the correct way to declare and raise an event in C#?
Remember the order: 'public event' then type then name.
Option A correctly declares an event and safely raises it using the null-conditional operator.
Which statement best explains how events improve program design?
Think about how events help parts of a program work together without knowing too much about each other.
Events enable loose coupling by letting objects notify others about changes without direct dependencies, improving flexibility and maintainability.