No need to construct a delegate object

  1. 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);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s