dev hedgehog
dev hedgehog

Reputation: 8791

Typed and untyped delegates

What is the difference between

var propertyResolver = Expression.Lambda<Func<Person, object>>(expr, arg).Compile();
string name = (string)propertyResolver(p);

and

var propertyResolver = Expression.Lambda(expr, arg).Compile();
string name = (string)propertyResolver(p);

In the second case there is some kind of "untyped" delegates.

What is that?

EDIT:

ParameterExpression arg = Expression.Parameter(p.GetType(), "x");
Expression expr = Expression.Property(arg, "Name");

Upvotes: 3

Views: 591

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500785

The first code is a call to Expression.Lambda<TDelegate>, which returns an Expression<TDelegate>, which has a Compile() method returning TDelegate. So the type of propertyResolver in your case is Func<Person, Object>.

The second code is a call to the non-generic Expression.Lambda method which returns a LambdaExpression. This has a Compile() method that just returns Delegate. So the type of propertyResolver in your case is Delegate - which is why propertyResolver(p) won't compile.

Upvotes: 2

Related Questions