So let's say that I have a method of the following manners:
public T Get<T, U>(Expression<Func<T, U>> expr) {
// use the expression to retrieve cool stuff.
}
Now I want to invoke this method with only string values. That is, I need to compile an expression in runtime.
So, let's say that I have a class Foo:
public class Foo {
public string Name { get; set; }
}
and then have another class Bar:
public class Bar {
public string AnotherName { get; set; }
}
Now I want to compile an expression that would look like this:
Foo foo = new Foo { Name = "AName" };
Expression<Func<Bar, string>> expr = p => p.AnotherName == foo.Name;
However, the only information I got in runtime is:
- The name of the property "AnotherName"
- The name of the class "Bar"
- The value of the property "Name" in Foo
- The name of the class "Foo"
So, after some lurking I found out that there is a System.Linq.Dynamic library where I could compile an expr of the string:
@"Bar.AnotherName == AName";
Example:
var sourceValue = "AName";
var targetClassName = "Bar";
var targetPropertyName = "AnotherName";
var expr = string.Format("{0}.{1} == {2}",
targetClassName, targetPropertyName, sourceValue);
var p = Expression.Parameter(typeof(Bar), "Target");
var e = System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { p }, null, expr);
var lambda = e.Compile();
However, this will only result in a delegate to a lambda expression.
My question is now, is it actually possible to invoke the Get method by creating an expression in runtime like this?
CSharpCodeProvider. Maybe overkill, but it will solve your problem.