What is the output of this C# program that uses a delegate as a callback?
using System; public delegate void Notify(string message); class Program { static void Main() { Notify notifier = PrintMessage; notifier("Hello from delegate!"); } static void PrintMessage(string msg) { Console.WriteLine(msg); } }
Look at how the delegate is assigned and invoked.
The delegate Notify points to the method PrintMessage. When invoked, it calls PrintMessage with the given string, printing it.
What will be the output of this C# program using a multicast delegate as a callback?
using System; public delegate void Notify(string message); class Program { static void Main() { Notify notifier = PrintMessage; notifier += PrintMessageUpper; notifier("Hello!"); } static void PrintMessage(string msg) { Console.WriteLine(msg); } static void PrintMessageUpper(string msg) { Console.WriteLine(msg.ToUpper()); } }
Multicast delegates call all methods in their invocation list.
The delegate notifier calls both PrintMessage and PrintMessageUpper in order, so both lines print.
What error does this C# program produce when run?
using System; public delegate void Notify(string message); class Program { static void Main() { Notify notifier = null; notifier("Test message"); } }
What happens if you call a delegate variable that is null?
Calling a null delegate causes a NullReferenceException at runtime because there is no method to invoke.
Which statement best describes the use of delegates as callbacks in C#?
Think about what delegates enable in terms of method references and callbacks.
Delegates are type-safe references to methods. They can be passed around and invoked later, which is the core of callback patterns.
Which option correctly declares a delegate type for a callback that takes an int and returns a string?
Remember the syntax for declaring delegates: public delegate ReturnType Name(ParameterList);
Option C uses the correct syntax for declaring a delegate with a return type and parameter.