roslyn: Anonymous function that captures no outer variables is not static

In VS2013, an anonymous function that captures no outer variables is compiled as a static method. In VS2015, it is non-static. This is a breaking change for our code. Test case:

using System;
using System.Linq.Expressions;

namespace AnonymousMethodStaticTest
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Testing method");
      CallAction(Method);

      Console.WriteLine("Testing anonymous function");
      Action action = () => { };
      CallAction(action);
    }

    static void Method()
    {
    }

    static void CallAction(Action action)
    {
      Console.WriteLine(action.Method.IsStatic);

      try
      {
        Expression callExpression = Expression.Call(action.Method);
      }
      catch
      {
        Console.WriteLine("Exception occurred because action.Method.IsStatic == false");
      }
    }
  }
}

In VS2013, this produces:

Testing method True Testing anonymous function True

In VS2015, this produces:

Testing method True Testing anonymous function False Exception occurred because action.Method.IsStatic == false

Expected: VS2015 output should match VS2013 output.

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 27 (14 by maintainers)

Most upvoted comments

The C# specification doesn’t say whether the methods generated from lambda expressions are static or not, code which assumes either is wrong.