Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous method in static class is non-static? How to invoke it?

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?

like image 536
Jens Avatar asked Feb 22 '17 11:02

Jens


People also ask

Can I call static method in non static method?

Characteristics of Static Methods A static method can call only other static methods; it cannot call a non-static method.

How can you invoke a non static method in Java?

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().

How do you call a non static class from a static class?

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.

Why is it illegal for static method to invoke a non static method?

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.


1 Answers

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.

like image 172
Damien_The_Unbeliever Avatar answered Sep 28 '22 05:09

Damien_The_Unbeliever