I'm trying to understand an edge-case of compiler powered delegate caching to avoid memory allocation.
For example, to my understanding, this delegate gets cached to a single instance and reused, because it doesn't close over any local variable:
int[] set = new [] { 1, 2, 3, 4, 5, 6 };
var subset = set.Where(x => x % 2 == 0);
Now I have some cases where my generated code might want to invoke a delegate directly, so an anonymous method is not valid C#, like so:
var result = (x => x % 2 == 0).Invoke(5); // Invalid
To circumvent this, I see two options:
- Using the constructor:
var result = (new Func<int, bool>(x => x % 2 == 0)).Invoke(5);
- Casting the anonymous delegate:
var result = ((Func<int, bool>)(x => x % 2 == 0)).Invoke(5);
I'm assuming the compiler will not cache the delegate in option #1, but I'm not sure if it will in #2.
Is this documented anywhere?