Challenge - 5 Problems
Action Delegate Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of Action delegate with multiple methods
What is the output of this C# code using an Action delegate with multiple methods?
C Sharp (C#)
using System; class Program { static void Main() { Action action = Method1; action += Method2; action(); } static void Method1() { Console.WriteLine("Hello"); } static void Method2() { Console.WriteLine("World"); } }
Attempts:
2 left
💡 Hint
Think about how Action delegates combine multiple methods and invoke them in order.
✗ Incorrect
The Action delegate can hold references to multiple methods. When invoked, it calls each method in the order they were added. So Method1 prints "Hello" first, then Method2 prints "World".
❓ Predict Output
intermediate1:30remaining
Action delegate with parameters output
What will be printed when this C# program runs?
C Sharp (C#)
using System; class Program { static void Main() { Action<string> greet = name => Console.WriteLine($"Hi, {name}!"); greet("Alice"); } }
Attempts:
2 left
💡 Hint
Look at how the lambda uses the parameter to print the greeting.
✗ Incorrect
The Action delegate takes a string parameter. The lambda prints "Hi, " followed by the name passed. So it prints "Hi, Alice!".
🔧 Debug
advanced2:00remaining
Why does this Action delegate cause a runtime error?
Consider this code snippet. Why does it throw a NullReferenceException at runtime?
C Sharp (C#)
using System; class Program { static Action action; static void Main() { action(); } }
Attempts:
2 left
💡 Hint
Check if the delegate variable was assigned before calling it.
✗ Incorrect
The 'action' delegate is declared but never assigned a method. Calling it causes a NullReferenceException because it points to null.
📝 Syntax
advanced1:30remaining
Identify the syntax error in Action delegate declaration
Which option contains a syntax error when declaring an Action delegate?
Attempts:
2 left
💡 Hint
Check the syntax inside the lambda body for missing punctuation.
✗ Incorrect
Option C is missing a semicolon after Console.WriteLine(n) inside the lambda block, causing a syntax error.
🚀 Application
expert2:30remaining
Using Action delegate to modify a list
Given this code, what is the final content of the list 'numbers' after invoking the Action delegate?
C Sharp (C#)
using System; using System.Collections.Generic; class Program { static void Main() { List<int> numbers = new() {1, 2, 3}; Action<List<int>> addNumbers = list => { list.Add(4); list.Add(5); }; addNumbers(numbers); numbers.Remove(2); addNumbers(numbers); Console.WriteLine(string.Join(",", numbers)); } }
Attempts:
2 left
💡 Hint
Remember the list is modified twice by the Action delegate and once by Remove.
✗ Incorrect
Initially numbers = [1,2,3]. First addNumbers adds 4 and 5: [1,2,3,4,5]. Then Remove(2): [1,3,4,5]. Then addNumbers again adds 4 and 5: [1,3,4,5,4,5].