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

Delegate declaration and instantiation 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 represents references to methods with a specific parameter list and return type. It allows methods to be passed as parameters or assigned to variables.
Click to reveal answer
beginner
How do you declare a delegate that takes an int and returns void?
You declare it like this:
public delegate void MyDelegate(int number);
Click to reveal answer
beginner
How do you instantiate a delegate to point to a method named 'PrintNumber'?
You instantiate it like this:
MyDelegate d = new MyDelegate(PrintNumber);
or simply
MyDelegate d = PrintNumber;
Click to reveal answer
intermediate
Can a delegate hold references to multiple methods?
Yes, delegates can hold references to multiple methods. This is called a multicast delegate, and it calls all methods in its invocation list when invoked.
Click to reveal answer
beginner
What happens when you invoke a delegate?
When you invoke a delegate, it calls the method(s) it references with the provided arguments, and returns the result if the method has a return type.
Click to reveal answer
How do you declare a delegate that returns an int and takes no parameters?
Adelegate void MyDelegate(int);
Bpublic int delegate MyDelegate();
Cpublic delegate int MyDelegate();
Ddelegate MyDelegate int();
Which of the following is a valid way to instantiate a delegate named 'MyDelegate' pointing to method 'Show'?
AMyDelegate d = new MyDelegate(Show);
BMyDelegate d = Show();
CMyDelegate d = delegate Show();
DMyDelegate d = new Show();
What is a multicast delegate?
AA delegate that can reference multiple methods.
BA delegate that returns multiple values.
CA delegate that can only reference one method.
DA delegate that is declared inside a class.
What keyword is used to declare a delegate in C#?
Aaction
Bevent
Cfunc
Ddelegate
If a delegate references multiple methods, what happens when you invoke it?
AOnly the last method is called.
BAll referenced methods are called in order.
COnly the first method is called.
DAn error occurs.
Explain how to declare and instantiate a delegate in C# with an example.
Think about how you define a delegate type and then create an object of that type pointing to a method.
You got /4 concepts.
    Describe what happens when you invoke a multicast delegate.
    Consider how a delegate can hold more than one method and what that means when you call it.
    You got /4 concepts.