Anonymous methods work exactly the same way as normal methods - if the JIT compiler decides to inline them, they can be inlined.
However, most likely, you're not calling an anonymous method directly - you are invoking a delegate that points to the anonymous method. In that case, as with any other delegate invokation, the compiler can't inline anything since it doesn't know at compile-time (or JIT-time) which method is actually going to be invoked.
I guess you're confused with how generics work in .NET, rather than anonymous methods explicitly, especially contrasted with C++'s templates - for example, if I do collection.Select(i => i.SomeProperty)
in C#, there's still only one method Select
[1]; how would you inline the i => i.SomeProperty
method when there's other Select
calls that take different functions as arguments? In contrast, using templates in C++ allows inlining "function" arguments, since the templates are only a compile-time code generation feature; every use of an analogous Select
template in C++ would give you a separate piece of code, no method invocation is involved.
Needless to say, this is just an implementation detail. It would be valid for a future compiler to inline the method call, by pretending it isn't a delegate and inlining the Select
method itself.
[1] - Technically, during JIT compilation, there may be multiple versions of the Select
method for different type arguments - this has no bearing on this scenario, though; it still doesn't make a different method for every possible argument.