I would like to make some heap allocation free methods for performing some operations. Some of these methods accept a delegate as their parameters. My concern is about what if passing in a lambda function to these methods would cause heap allocations. For example, consider the following code:
public SomeItem FindItem(Predicate<SomeItem> predicate)
{
// Return something by calling predicate(someItem) multiple times.
}
private void DoSomething()
{
var myItem = FindItem(item => item.IsValid);
// Do something.
}
Considering the code sample above, would a call to DoSomething()
cause any heap allocation, in the current version of C# and .NET?
And what about alternatives? Are there types of delegates or conventions for lambda functions in .NET that are heap allocation free? I’ve read about a ValueAction<T>
proposal, somewhere around .NET Core 2.1, but I don’t know if it was actually implemented, or if something like it already exists in .NET 8.