Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do lambda expressions use reflection?

To be sure that I understand could someone confirm that lambda expressions use reflection?

like image 835
Bastien Vandamme Avatar asked Nov 04 '25 10:11

Bastien Vandamme


2 Answers

They can, but they are not required to. If they are compiled to a delegate, then no reflection is necessary: however, if they are compiled to ab expression tree, then an expression tree is absolutely reflection-based. Some parts of expression trees can be assembled directly from metadata tokens (ldtoken) - in particular methods (including operators and getters/setters, and types) - but some other parts cannot . This includes properties (PropertyInfo cannot be loaded by token) - so the IL for a compiled lambda can explicitly include GetProperty etc.

But however it is loaded (token or reflection), an expression tree is expressed in terms of reflection (MemberInfo, etc). This might later be compiled, or might be analysed by a provider.

To help performance, the expression compiler may cache some or all of the expression tree, and re-use it.

like image 179
Marc Gravell Avatar answered Nov 06 '25 00:11

Marc Gravell


Lambda expressions are turned by the compiler into either anonymous functions or expression trees. Since reflection can only be performed at runtime it doesn't come into the picture at all when considering what the compiler does with them in either case.

At runtime, lambda expressions might result in reflection being used under very specific circumstances:

For anonymous functions: if you write an anonymous function that explicitly reflects on something then the lambda will perform that reflection when invoked. This is of course the same as if you were reflecting from within a "proper" method.

For expression trees (i.e. values of type Expression<TDelegate> for some TDelegate): using them at runtime when working with an IQueryable might result in reflection being used by the query provider. For example, assume that you do:

var user = new User { Id = 42 };
var posts = Queryable.Posts.Where(p => p.UserId == user.Id);

When posts is about to be materialized the query provider sees that it must find those posts with a UserId equal to the Id of the variable user. Since that id has a specific known value at runtime, the query provider needs to fish it out of user. One way it might decide to do that is through reflection.

like image 20
Jon Avatar answered Nov 06 '25 00:11

Jon