Lambda is seen as a private delegate in Visual Studio 2015

I was surprised that there would be any difference in execution time between the two delegates ( fn1and fn2):

static int SomeStaticMethod(int x) { return x; }

// fn1.Target == null in this case
Func<int, int> fn1 = SomeStaticMethod;

// fn2.Target != null in this case
Func<int, int> fn2 = x => x;

But, apparently, the second lambda is considered as an instance method, because its property is Targetnot null. And it was considered differently before I switched to Visual Studio 2015 (in VS2012, I am sure that it was considered as a static method).

Is there a reason why a lambda without closures is considered as a private delegate (i.e. instance method) in C #? I thought maybe this is a debugger adding some things, but this also happens in versions.

(Clarification)

The fact is that I had a method that created a general delegate for quick conversion from enums to ints (without boxing):

private static Func<int, TEnum> CreateIntToEnumDelegate()
{
    Func<int, int> lambda = x => x;
    return Delegate.CreateDelegate(typeof(Func<int, TEnum>), lambda.Method) 
        as Func<int, TEnum>;
}

and he no longer worked for Roslyn, because the "instance" of the lambda became incompatible with the signature of the delegate. So instead, I had to use the method static, it doesn't matter.

But what bothers me is that it was impossible to catch at compile time. This thread describes similar issues, by the way, now I was looking for "Roslyn delegates . "

+4
source share
1 answer
+3

Source: https://habr.com/ru/post/1617677/


All Articles