I am running the following program on two different machines:
static class Program
{
static void Main(string[] args)
{
Func<int> lambda = () => 5;
Console.WriteLine(lambda.GetMethodInfo().IsStatic);
Console.ReadLine();
}
}
On one machine, with .NET 4.5 and Visual Studio 2012 installed this prints "true", on another one, with .NET Framework 4.6.2 and Visual Studio 2015 it prints "false".
I thought that anonymous methods were static if they are defined in a static context. Did this change (in a documented way) during some of the last framework updates?
What I need to do, is to use Expression.Call
on lambda.GetMethodInfo()
, and in the non-static case this requires an instance on which the lambda is defined.
If I wanted to use lambda.GetMethodInfo().Invoke
I would face the same problem.
How can I get such an instance?
Characteristics of Static Methods A static method can call only other static methods; it cannot call a non-static method.
To call a non-static method from main in Java, you first need to create an instance of the class, post which we can call using objectName. methodName().
We can call non-static method from static method by creating instance of class belongs to method, eg) main() method is also static method and we can call non-static method from main() method . Even private methods can be called from static methods with class instance.
A non-static method is a method that executes in the context of an instance . Without an instance it makes no sense to call one, so the compiler prevents you from doing so - ie it's illegal.
Bear in mind that this (lambdas) is a compiler feature so the runtime framework version won't make a difference. Also, because this is a compiler feature, it's not all that surprising that there's a difference between 2012 and 2015 (when Roslyn was introduced which replaced most of the existing compiler infrastructure).
I cannot give a solid reason for why it would have been specifically changed here (although I know several changes were made to enabled Edit-and-Continue to work in more contexts), but it has never been contractual about how lambdas are implemented.
How can I get such an instance?
Well, lambda
is a Delegate
, and that's always exposed a Target
property which references an instance when the delegate is so bound.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With