Consider the following C# code snippet. What will be printed when the program runs?
using System; class Program { public delegate void Notify(); public event Notify OnNotify; public void Trigger() { OnNotify?.Invoke(); } static void Main() { Program p = new Program(); p.OnNotify += () => Console.WriteLine("Event triggered!"); p.Trigger(); } }
Check if the event is subscribed before invoking.
The event OnNotify is subscribed with a lambda that prints "Event triggered!". The Trigger method invokes the event safely using the null-conditional operator ?., so the output is printed.
What error will this code produce?
using System; class Program { public event Action OnAction = () => {}; static void Main() { Program p = new Program(); p.OnAction(); } }
Events cannot be assigned directly with initial values.
In C#, events cannot be initialized directly with a delegate. This causes a compile-time error.
Examine the code below. Why does it throw an exception at runtime?
using System; class Program { public event Action OnEvent; public void Raise() { OnEvent(); } static void Main() { Program p = new Program(); p.Raise(); } }
Check if the event is null before invoking.
The event OnEvent has no subscribers, so it is null. Invoking it directly causes a NullReferenceException.
Which of the following is the correct way to declare an event using a custom delegate in C#?
Remember the order: delegate declaration first, then event declaration.
Option C correctly declares a delegate type and then an event of that delegate type.
Given the following code, how many methods are subscribed to the OnChange event after execution?
using System; class Program { public event Action OnChange; public void Subscribe() { OnChange += Handler1; OnChange += Handler2; OnChange -= Handler1; OnChange += Handler3; } void Handler1() { } void Handler2() { } void Handler3() { } static void Main() { Program p = new Program(); p.Subscribe(); Console.WriteLine(p.OnChange?.GetInvocationList().Length ?? 0); } }
Consider the += and -= operations on the event.
Handler1 is added then removed, Handler2 and Handler3 remain subscribed, so 2 subscribers remain.