- Why it is possible not to specify a class to pass parameters to an anonymous method.
- 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);