Challenge - 5 Problems
Delegate Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of delegate invocation
What is the output of this C# code that uses a delegate to call a method?
C Sharp (C#)
using System; public delegate void Notify(string message); class Program { static void Main() { Notify notify = ShowMessage; notify("Hello, delegate!"); } static void ShowMessage(string msg) { Console.WriteLine(msg); } }
Attempts:
2 left
💡 Hint
Look at how the delegate calls the method ShowMessage with a string argument.
✗ Incorrect
The delegate 'Notify' points to the method 'ShowMessage'. When invoked with a string, it calls ShowMessage which prints the message.
🧠 Conceptual
intermediate1:30remaining
Why use delegates in C#?
Which of these best explains why delegates are needed in C#?
Attempts:
2 left
💡 Hint
Think about how you might want to call different methods dynamically.
✗ Incorrect
Delegates let you treat methods like variables, so you can pass them around and call them later, enabling callbacks and event handling.
❓ Predict Output
advanced2:30remaining
Multicast delegate output
What will be the output of this C# program using a multicast delegate?
C Sharp (C#)
using System; public delegate void Notify(); class Program { static void Main() { Notify notify = First; notify += Second; notify(); } static void First() { Console.WriteLine("First called"); } static void Second() { Console.WriteLine("Second called"); } }
Attempts:
2 left
💡 Hint
Multicast delegates call all methods in the order they were added.
✗ Incorrect
The delegate 'notify' calls First then Second because both methods are added to the invocation list.
❓ Predict Output
advanced2:30remaining
Delegate with return value behavior
What is the output of this C# code where a delegate has multiple methods with return values?
C Sharp (C#)
using System; public delegate int Calculate(int x, int y); class Program { static void Main() { Calculate calc = Add; calc += Multiply; int result = calc(3, 4); Console.WriteLine(result); } static int Add(int a, int b) { return a + b; } static int Multiply(int a, int b) { return a * b; } }
Attempts:
2 left
💡 Hint
When a multicast delegate returns a value, only the last method's return is used.
✗ Incorrect
The delegate calls Add then Multiply, but only Multiply's return value (3*4=12) is stored in result.
🧠 Conceptual
expert2:00remaining
Delegate use in event handling
Why are delegates essential for event handling in C#?
Attempts:
2 left
💡 Hint
Think about how events notify multiple methods when something happens.
✗ Incorrect
Delegates let events keep a list of methods to call when triggered, enabling dynamic and flexible event responses.