Bird
Raised Fist0
C Sharp (C#)programming~20 mins

Delegates as callback pattern in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Delegate Callback Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of delegate callback invocation

What is the output of this C# program that uses a delegate as a callback?

C Sharp (C#)
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);
    }
}
AHello from delegate!
BSystem.Delegate
CCompile-time error
DRuntime exception
Attempts:
2 left
💡 Hint

Look at how the delegate is assigned and invoked.

❓ Predict Output
intermediate
2:00remaining
Delegate callback with multiple methods

What will be the output of this C# program using a multicast delegate as a callback?

C Sharp (C#)
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());
    }
}
AHELLO!\nHello!
BCompile-time error
CHello!
DHello!\nHELLO!
Attempts:
2 left
💡 Hint

Multicast delegates call all methods in their invocation list.

🔧 Debug
advanced
2:00remaining
Identify the runtime error in delegate callback

What error does this C# program produce when run?

C Sharp (C#)
using System;

public delegate void Notify(string message);

class Program
{
    static void Main()
    {
        Notify notifier = null;
        notifier("Test message");
    }
}
ANullReferenceException
BCompile-time error: delegate not assigned
CArgumentNullException
DNo error, prints 'Test message'
Attempts:
2 left
💡 Hint

What happens if you call a delegate variable that is null?

🧠 Conceptual
advanced
2:00remaining
Delegate callback pattern usage

Which statement best describes the use of delegates as callbacks in C#?

ADelegates automatically run all methods in parallel threads.
BDelegates allow methods to be passed as parameters and called later, enabling flexible callback patterns.
CDelegates are used only to store multiple unrelated methods without parameters.
DDelegates replace all event handling mechanisms in C#.
Attempts:
2 left
💡 Hint

Think about what delegates enable in terms of method references and callbacks.

📝 Syntax
expert
2:00remaining
Correct delegate declaration for callback with return value

Which option correctly declares a delegate type for a callback that takes an int and returns a string?

Adelegate string Callback(int value) {}
Bpublic delegate void Callback(int value) => string;
Cpublic delegate string Callback(int value);
Dpublic Callback delegate string(int value);
Attempts:
2 left
💡 Hint

Remember the syntax for declaring delegates: public delegate ReturnType Name(ParameterList);

Practice

(1/5)
1. What is the main purpose of using delegates as a callback pattern in C#?
easy
A. To handle exceptions automatically
B. To create new classes dynamically
C. To pass methods as parameters and execute them later
D. To convert data types implicitly

Solution

  1. Step 1: Understand delegate usage

    Delegates allow methods to be passed as parameters to other methods.
  2. Step 2: Identify callback purpose

    This passing enables callbacks, which run code after some work is done.
  3. Final Answer:

    To pass methods as parameters and execute them later -> Option C
  4. Quick Check:

    Delegates = method parameters for callbacks [OK]
Hint: Delegates let you pass methods to run later [OK]
Common Mistakes:
  • Confusing delegates with classes
  • Thinking delegates handle exceptions
  • Assuming delegates convert data types
2. Which of the following is the correct syntax to declare a delegate that takes an int and returns void?
easy
A. MyDelegate delegate void(int number);
B. void delegate MyDelegate(int number);
C. delegate MyDelegate void(int number);
D. delegate void MyDelegate(int number);

Solution

  1. Step 1: Recall delegate declaration syntax

    The correct syntax is: delegate returnType DelegateName(parameterList);
  2. Step 2: Match syntax to options

    delegate void MyDelegate(int number); matches this pattern: delegate void MyDelegate(int number);
  3. Final Answer:

    delegate void MyDelegate(int number); -> Option D
  4. Quick Check:

    delegate returnType Name(params) = delegate void MyDelegate(int number); [OK]
Hint: Remember: delegate returnType Name(params) [OK]
Common Mistakes:
  • Placing 'void' before 'delegate'
  • Swapping delegate and return type order
  • Misplacing delegate keyword after name
3. What will be the output of the following code?
delegate void Callback(string message);  
class Program {
  static void Main() {
    Callback cb = msg => Console.WriteLine($"Hello, {msg}!");
    RunProcess(cb);
  }
  static void RunProcess(Callback callback) {
    Console.WriteLine("Starting process...");
    callback("World");
    Console.WriteLine("Process finished.");
  }
}
medium
A. Starting process... Hello, World! Process finished.
B. Hello, World! Starting process... Process finished.
C. Starting process... Process finished. Hello, World!
D. Process finished. Starting process... Hello, World!

Solution

  1. Step 1: Trace method calls in Main and RunProcess

    Main creates a callback that prints "Hello, {msg}!" and passes it to RunProcess. RunProcess prints "Starting process...", calls callback with "World", then prints "Process finished.".
  2. Step 2: Determine output order

    Output lines are: "Starting process...", "Hello, World!", "Process finished." in that order.
  3. Final Answer:

    Starting process... Hello, World! Process finished. -> Option A
  4. Quick Check:

    Callback runs between start and finish prints [OK]
Hint: Callbacks run where invoked inside method [OK]
Common Mistakes:
  • Assuming callback runs before 'Starting process...'
  • Mixing output order
  • Ignoring lambda execution timing
4. Identify the error in this code snippet using delegates as callbacks:
delegate void Notify();
class Test {
  static void Main() {
    Notify n = NotifyMethod;
    Run(n);
  }
  static void Run(Notify callback) {
    callback();
  }
  static void NotifyMethod(string message) {
    Console.WriteLine(message);
  }
}
medium
A. Delegate is not instantiated correctly
B. Delegate signature does not match method signature
C. Callback method is not called
D. Missing return statement in NotifyMethod

Solution

  1. Step 1: Compare delegate and method signatures

    Delegate Notify expects a method with no parameters and void return. NotifyMethod takes a string parameter, so signatures differ.
  2. Step 2: Understand delegate assignment rules

    Assigning NotifyMethod to Notify delegate causes a compile-time error due to signature mismatch.
  3. Final Answer:

    Delegate signature does not match method signature -> Option B
  4. Quick Check:

    Delegate and method signatures must match [OK]
Hint: Delegate and method signatures must match exactly [OK]
Common Mistakes:
  • Ignoring parameter mismatch
  • Thinking delegate instantiation is wrong
  • Assuming missing return causes error here
5. You want to create a method ProcessData that takes an integer array and a delegate callback to process each element asynchronously. Which approach correctly uses delegates as callbacks to print each element after processing?
hard
A. Define a delegate Action<int> and call it inside a loop with Task.Run(() => callback(item))
B. Use a delegate with no parameters and call it once after processing all elements
C. Pass a delegate that returns int and ignore its return value
D. Use a delegate that takes a string but pass integers directly

Solution

  1. Step 1: Identify delegate type for element processing

    Since each element is an int and we want to process it, Action<int> fits as it takes int and returns void.
  2. Step 2: Use asynchronous calls inside loop

    Calling Task.Run(() => callback(item)) runs the callback asynchronously for each element.
  3. Final Answer:

    Define a delegate Action<int> and call it inside a loop with Task.Run(() => callback(item)) -> Option A
  4. Quick Check:

    Delegate matches parameter and async call runs callback per item [OK]
Hint: Use Action<int> and async calls inside loop [OK]
Common Mistakes:
  • Using delegate with wrong parameters
  • Calling callback only once instead of per item
  • Ignoring async execution
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard