Question

For example i have a method with func inside:

private void Method()
{
    Func<int, string> myFunc => (int) { return int.ToString();}
    var res = myFunc(42);
}

Func will be compiled 1 time or every time when method will be called?

Also please share some links if you have such, because this is a kind of argue

Was it helpful?

Solution

Looks like you are confusing expressions:

Expression<Func<int, string>> myFuncExpr = someInt => someInt.ToString();

and delegates:

Func<int, string> myFunc = someInt => someInt.ToString();

They have the similar declaration syntax, when using lambdas, but the expression tree won't compile into delegate, until you call myFuncExpr.Compile(). Every time you call Compile, the compilation will take place, because expression tree is a way to represent a code (C# code in particular), not a code itself.

From the other hand, the delegate will be compiled once with the rest of source code from your assembly. From the point of compiler, lambda here is just another way to declare a method body, that is, the code itself. So, there's no any reason to compile it somehow differently.

OTHER TIPS

This is how it is compiled

[CompilerGenerated]
private static Func<int, string> CS$<>9__CachedAnonymousMethodDelegate1;

private void Method()
{
    Func<int, string> myFunc = (CS$<>9__CachedAnonymousMethodDelegate1 != null) ? CS$<>9__CachedAnonymousMethodDelegate1 : (CS$<>9__CachedAnonymousMethodDelegate1 = new Func<int, string>(Program.<Method>b__0));
    string res = myFunc(0x2a);
}

So it clear that it gets created only once and stored in a static field.

Also note that even though this is instance method delegate is made static. So it happens exactly once in an AppDomain's life.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top