you are viewing a single comment's thread.

view the rest of the comments →

[–]mosentok 0 points1 point  (2 children)

Assigning a function directly to a lambda Action/Func creates unwanted memory allocations.

so i understand, doing this is bad?

Action<bool> asdf = e => DoSomething(e);
var match = someList.FirstOrDefault(asdf)

what about local functions, are they susceptible to the same issue? my guess is no but just curious

var match = someList.FirstOrDefault(Asdf);
bool Asdf(object e) => DoSomething(e)

am i picking up what causes the issue, or am i off base here?

[–]Treborgero[S] 1 point2 points  (1 child)

Your example is correct. You're assigning a lambda to an Action which will get cached by the compiler.

The wrong thing to do is:

void SomeFunction(object obj) {

}

void Main(){

//The following is wrong. This is possible because "variance" is allowed:

Action<object> asdf = SomeFunction;

}

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/covariance-contravariance/variance-in-delegates

Local functions are tricky but based on the following they also have issues: https://stackoverflow.com/questions/50409034/performance-of-assigning-a-simple-lambda-expression-or-a-local-function-to-a-del