Consider the following C# code implementing a basic publisher-subscriber pattern. What will be printed when the program runs?
using System; public class Publisher { public event Action OnChange; public void RaiseEvent() { OnChange?.Invoke(); } } public class Subscriber { public void Respond() { Console.WriteLine("Subscriber received event."); } } public class Program { public static void Main() { Publisher pub = new Publisher(); Subscriber sub = new Subscriber(); pub.OnChange += sub.Respond; pub.RaiseEvent(); } }
Look at how the event is subscribed and invoked.
The subscriber method Respond is attached to the publisher's event OnChange. When RaiseEvent is called, it invokes OnChange, triggering Respond and printing the message.
What will be the output or behavior of this code when RaiseEvent is called but no subscriber is attached?
using System; public class Publisher { public event Action OnChange; public void RaiseEvent() { OnChange?.Invoke(); Console.WriteLine("Event raised."); } } public class Program { public static void Main() { Publisher pub = new Publisher(); pub.RaiseEvent(); } }
Check the null-conditional operator usage.
The event OnChange is null because no subscriber is attached. The null-conditional operator ?. prevents invocation if null, so no error occurs. The line Console.WriteLine("Event raised."); still runs.
What error will this code produce when compiled or run?
using System; public class Publisher { public event Action OnChange; public void RaiseEvent() { OnChange(); } } public class Program { public static void Main() { Publisher pub = new Publisher(); pub.RaiseEvent(); } }
Consider what happens if the event has no subscribers and is invoked directly.
The event OnChange is null because no subscriber is attached. Invoking it directly without checking for null causes a NullReferenceException at runtime.
Choose the correct statement about the publisher-subscriber pattern using C# events.
Think about how delegates and events work in C#.
Subscribers must attach methods that match the delegate signature of the event. Events cannot be invoked from outside their declaring class. Events do not queue messages automatically. Multiple events can share the same delegate type.
Given this code with two subscribers attached to the same event, what will be printed?
using System; public class Publisher { public event Action OnChange; public void RaiseEvent() { OnChange?.Invoke(); } } public class Program { public static void Main() { Publisher pub = new Publisher(); pub.OnChange += () => Console.WriteLine("First subscriber called."); pub.OnChange += () => Console.WriteLine("Second subscriber called."); pub.RaiseEvent(); } }
Events invoke subscribers in the order they were added.
The event OnChange calls subscribers in the order they were attached. So the first lambda prints first, then the second.