CORRECT ANSWERS 2024/2025
What is a delegate?
A delegate is a reference type that can be used to reference a method. It encapsulates
the method.
How is delegate declared?
public delegate void MyDelegate();
Give delegate code to reference:
public static int Number(int x)
{
return x;
}
public delegate int NumDel(int x);
NumDel d1 = new NumDel(Number);
d1(2);
Give delegate code that would call all three methods when the delegate is
invoked:
public static void method1(){}, public static void method2(){}, public void
method3(){}
public delegate void MethodDel();
, MethodDel d = new MethodDel(method1);
d += new MethodDel(method2);
Class m3 = new Class();
d+= new MethodDel(m3.method3);
d();
The method that a delegate references or encapsulates has to have the same
what?
The method and delegate must have the same signature/prototype
After a delegate is declared, how do we use it?
Like a class, create an instance of the delegate with static or instance method passed
as parameter.
Delegates are similar to what in c++?
Delegates are similar to a function pointer in c++
Describe how a delegate can be used to define callback methods?
A delegate can be used to define callback methods my passing the name of the event
handler to the delegate reference
Give basic code of how to combine a delegate and an event.
1. Declare delegate:
public delegate void MyDelegate();
2. Declare event:
public static event MyDelegate Myevent;