- What does the C# compiler generates to make possible to pass only method name as parameter without having to construct a delegate object wrapper?
Example 1:
class Program
{
private delegate void MyDelegate(int param);
static void Main(string[] args)
{
CallDelegate(CallbackMethod, 5);
//Output: 5
}
private static void CallDelegate(MyDelegate del, int param)
{
del(param);
}
private static void CallbackMethod(int param)
{
Trace.WriteLine(param);
}
}
To make possible to call delegate method without having to construct a delegate object the C# compiler generates IL code, so the delegate object is constructed implicitly.
Compiler generated code:
CallDelegate(new MyDelegate(Program.CallbackMethod), 5);