Consider this C# code where a class publishes an event and another class subscribes to it. What will be printed when TriggerEvent is called?
using System; public class Publisher { public event EventHandler? OnChange; public void TriggerEvent() { OnChange?.Invoke(this, EventArgs.Empty); } } public class Subscriber { public void Subscribe(Publisher pub) { pub.OnChange += HandleEvent; } private void HandleEvent(object? sender, EventArgs e) { Console.WriteLine("Event received!"); } } public class Program { public static void Main() { Publisher pub = new Publisher(); Subscriber sub = new Subscriber(); sub.Subscribe(pub); pub.TriggerEvent(); } }
Think about what happens when TriggerEvent calls OnChange?.Invoke and if any subscriber is attached.
The Subscriber attaches HandleEvent to the Publisher's OnChange event. When TriggerEvent is called, it invokes the event, which calls HandleEvent and prints "Event received!".
Choose the best description of the event-driven design pattern in programming.
Think about how components react to changes or actions in event-driven systems.
Event-driven design means components send events when something happens, and other components listen and react to those events, often asynchronously.
Examine the following C# code snippet. What error will occur when compiling or running it?
using System; public class Publisher { public event EventHandler OnChange; public void TriggerEvent() { OnChange(this, EventArgs.Empty); } } public class Program { public static void Main() { Publisher pub = new Publisher(); pub.TriggerEvent(); } }
Consider what happens if no subscriber is attached to the event and the event is invoked directly.
The event OnChange is not checked for null before invocation. Since no subscriber is attached, invoking it causes a NullReferenceException at runtime.
Choose the correct code snippet that declares a custom event and raises it properly.
Remember that events should be declared with the event keyword and invoked safely.
Option A correctly declares an event and raises it using the null-conditional operator to avoid exceptions if no subscribers exist.
Given this C# code where the same handler is subscribed twice to an event, how many times will the handler run when the event is triggered once?
using System; public class Publisher { public event EventHandler? OnChange; public void TriggerEvent() { OnChange?.Invoke(this, EventArgs.Empty); } } public class Program { public static void Main() { Publisher pub = new Publisher(); EventHandler handler = (sender, e) => Console.WriteLine("Handler called"); pub.OnChange += handler; pub.OnChange += handler; pub.TriggerEvent(); } }
Think about what happens if the same method is added twice to an event's invocation list.
In C#, adding the same handler twice means it will be called twice when the event is raised.