No need to define a callback method

  1. What does the C# compiler generates to make possible to define a callback method in-line.
  2. What does anonymous method term mean?
  3. What kinds of limitations have anonymous methods?
  4.  What does enforce the C# compiler to generate instance anonymous methods?

When the C# compiler sees the delegate keyword wherever a delegate object is expected it generates a new private method and implicitly gives a name for this method.

This new method is called anonymous method because the C# compiler gives a name for this method implicitly. The prototype of anonymous methods must match of the delegate’s signature.

Example 1:

    class Program

    {

        private delegate void MyDelegate(int param);

 

        static void Main(string[] args)

        {

CallDelegate(delegate(int param) { return param; }, 6);            //Output: 6

        }

 

        private static void CallDelegate(MyDelegate del, int param)

        {

            Trace.WriteLine(del(param));

        }

    }

 

Compiler generated code:

 

[CompilerGenerated]
private static MyDelegate CS$<>9__CachedAnonymousMethodDelegate1;

 

[CompilerGenerated]
private static int <Main>b__0(int param)
{
    return param;

}

 

The anonymous methods don’t allow defining any modifiers such as unsafe, public, etc. The anonymous methods don’t allow applying attributes.

In case of anonymous method doesn’t have references to instance members the C# compiler generates static anonymous method. Otherwise it generates a special class and an instance anonymous method inside this class.

Example 2:

    class Program

    {

        private delegate int MyDelegate(int param);

        private int _val = 5;

 

        static void Main(string[] args)

        {

            Program p = new Program();

            CallDelegate(delegate(int param) { return param + p._val; }, 6); //Output: 11

        }

 

        private static void CallDelegate(MyDelegate del, int param)

        {

            Trace.WriteLine(del(param));

        }

    }

 

Compiler generated code:

 

[CompilerGenerated]
private sealed class <>c__DisplayClass1
{
    // Fields
    public Program p;
 
    // Methods
    public int <Main>b__0(int param)
    {
        return (param + this.p._val);
    }

}

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