ECMA-334: 14.5.15.4 Anonymous method evaluation


Jump to: navigation, search
C# Language Specification
© 2006 ECMA International

14.5.15.4 Anonymous method evaluation

The run-time evaluation of an anonymous-method-expression produces a delegate instance which references the anonymous method and the (possibly empty) set of captured outer variables that are active at the time of the evaluation. When a delegate resulting from an anonymous-method-expression is invoked, the body of the anonymous method is executed. The code in the body is executed using the set of captured outer variables referenced by the delegate.

The invocation list of a delegate produced from an anonymous-method-expression contains a single entry. The exact target object and target method of the delegate are unspecified. In particular, it is unspecified whether the target object of the delegate is null, the this value of the enclosing function member, or some other object.

Evaluation of semantically identical anonymous-method-expressions with the same (possibly empty) set of captured outer variable instances is permitted (but not required) to return the same delegate instance. The term "semantically identical" is used here to mean that execution of the anonymous methods will produce, in all cases, the same effects given the same arguments. [Example: This rule permits code such as the following to be optimized.

delegate double Function(double x);
class Test
{
  static double[] Apply(double[] vector, Function func) {
    double[] result = new double[vector.Length];
    for (int i = 0; i < vector.Length; i++) {
      result[i] = func(vector[i]);
    }
    return result;
  }
  static void F(double[] vx, double[] vy) {
    double[] rx = Apply(vx, delegate(double x) {
      return Math.Sin(x);
    });
    double[] ry = Apply(vy, delegate(double y) {
    return Math.Sin(y);
    });
  ...
  }
}

Since the two anonymous method delegates have the same (empty) set of captured outer variables, and since the anonymous methods are semantically identical, the compiler is permitted to have the delegates refer to the same target method. Indeed, the compiler is permitted to return the very same delegate instance from both anonymous method expressions. end example]



Share this page
  • del.icio.us
  • Facebook
  • Google+
  • StumbleUpon