No need to specify a class to pass parameters to an anonymous method

  1. Why it is possible not to specify a class to pass parameters to an anonymous method.
  2. What does the C# compiler generates when anonymous method’s code contains references to instance objects outside the method?

Example 1:

    class Program

    {

 

        private delegate int MyDelegate(int param);

 

        static void Main(string[] args)

        {

 

            int numToDo = 255;

            int[] results = new int[numToDo];

 

            for (int i = 0; i < results.Length; i++)

            {

                CallDelegate(delegate(int n)

                {

                    results[n] = n * n;

                    return n;

                } , i);

            }

 

            Array.ForEach(results, Console.WriteLine);                

        }

 

        private static void CallDelegate(MyDelegate del, int param)

        {

            Trace.WriteLine(del(param));

        }

When an anonymous method code contains references to instance objects outside the methods the C# compiler generates a special class. This class contains public instance fields and public instance methods thus the CLR can create an instance of this class, initialize its members and call the anonymous method, so we don’t need to wrap instance members to pass parameters to anonymous methods.

Compiler generated code:

[CompilerGenerated]
private sealed class <>c__DisplayClass2
{
    // Fields
    public int[] results;
 
    // Methods
    public int <Main>b__0(int n)
    {
        this.results[n] = n * n;
        return n;
    }

}

private static void Main(string[] args)
{
    int numToDo = 0xff;
    int[] results = new int[numToDo];
    for (int i = 0; i < results.Length; i++)
    {
        CallDelegate(delegate (int n) {
            results[n] = n * n;
            return n;
        }, i);
    }
    Array.ForEach<int>(results, new Action<int>(Console.WriteLine));

}

 

Example 2:

 

String[] data = { "Gamma", "Alpha", "Beta" };

 

data = Array.ConvertAll<String, String>(data, delegate(string p) { return p.ToUpper(); });

Array.Sort(data, String.Compare);

Array.ForEach(data, Console.WriteLine); 

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