0

I am running Visual Studio 2015 Enterprise, .NET 4.6, and I wrote some code that relies on Delegates being static. I ran the exact code from this question, but I get "false":

static void Main(string[] args)
{
    Action<string> actionMethod = s => { Console.WriteLine("My Name is " + s); };

    // Always false
    Console.WriteLine(actionMethod.Method.IsStatic);

    Console.Read();
}

Is this a bug? Or does C# not guarantee that lambdas without nonlocal dependencies are made static?

Is there a workaround to determine if a lambda/delegate has nonlocal dependencies? My goal is to know if a lambda caught it's enclosing variables / uses a closure.

Community
  • 1
  • 1
Felk
  • 7,720
  • 2
  • 35
  • 65
  • 2
    See [Delegate caching behavior changes in Roslyn](http://stackoverflow.com/questions/30897647/delegate-caching-behavior-changes-in-roslyn) for an explanation as to why this change was made. – Mike Zboray Jan 26 '16 at 16:56

1 Answers1

2

Or does C# not guarantee that lambdas without nonlocal dependencies are made static?

It makes no such guarantee. That was an implementation detail of some versions of the compiler; one that it has no obligation to continue with going forward. As you have seen, they've changed that implementation detail.

Servy
  • 202,030
  • 26
  • 332
  • 449