0
0
C Sharp (C#)programming~5 mins

Delegates as callback pattern in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a delegate in C#?
A delegate is a type that holds references to methods with a specific signature. It allows methods to be passed as parameters or assigned to variables.
Click to reveal answer
beginner
How does a delegate enable the callback pattern?
A delegate lets you pass a method as an argument to another method. The receiving method can then call the passed method later, acting as a callback.
Click to reveal answer
intermediate
Show a simple example of a delegate used as a callback.
public delegate void Notify(string message);

public class Process {
    public void Start(Notify callback) {
        // Do some work
        callback("Process finished");
    }
}

// Usage
Process p = new Process();
p.Start(msg => Console.WriteLine(msg));
Click to reveal answer
intermediate
What is the benefit of using delegates for callbacks?
Delegates provide flexibility by allowing different methods to be called without changing the caller code. This supports loose coupling and reusable code.
Click to reveal answer
advanced
Can delegates point to multiple methods? What is this called?
Yes, delegates can point to multiple methods. This is called a multicast delegate. When invoked, all methods are called in order.
Click to reveal answer
What does a delegate in C# represent?
AA class that inherits from another class
BA variable that stores data
CA type of loop
DA reference to a method with a specific signature
How do delegates support the callback pattern?
ABy creating new classes dynamically
BBy storing data in arrays
CBy allowing methods to be passed as parameters and called later
DBy running code in parallel automatically
What keyword is used to declare a delegate in C#?
Afunction
Bdelegate
Ccallback
Devent
What happens when a multicast delegate is invoked?
AAll methods assigned to it are called in order
BOnly the first method is called
CIt throws an error
DIt returns a list of methods
Which of these is a benefit of using delegates for callbacks?
AThey allow loose coupling between caller and callee
BThey increase program size significantly
CThey prevent any method from being called
DThey make code run slower always
Explain how delegates enable the callback pattern in C#.
Think about how you can give a method to another method to call back.
You got /4 concepts.
    Describe the difference between a single-cast and multicast delegate.
    Consider how many methods a delegate can point to.
    You got /4 concepts.