As noted in Section 3.6.3, C# has unusually sophisticated support for firstclass subroutines. Among other things, it allows delegates to be instantiated
from anonymous nested methods, and gives local variables and parameters
unlimited extent when they may be needed by such a delegate. Consider the
implications of these features in the following C# program:
using System;
public delegate int UnaryOp(int n);
// type declaration: UnaryOp is a function from ints to ints
public class Foo {
static int a = 2;
static UnaryOp b(int c) {
int d = a + c;
Console.WriteLine(d);
return delegate(int n) { return c + n; };
}
public static void Main(string[] args) {
Console.WriteLine(b(3)(4));
}
}
What does this program print? Which of a, b, c, and d, if any, is likely to be
statically allocated? Which could be allocated on the stack? Which would
need to be allocated in the heap? Explain.