willem
willem

Reputation: 27037

In .NET how to dynamically evaluate a complex expression against an object?

In C#, imagine I have the following object:

var myObject = new
{
    Val = new[]
    {
        new { ArrVal = "three1"},
        new { ArrVal = "three2"}
    }
};

How would I dynamically evaluate the following expression against the object? (the expression is a string)

"Val[1].ArrVal"

In this case I would expect the expression to return "three2". I'd like to write a method with the following signature:

object GetValue(string expression, object objectToExtractValueFrom)

Can I do this with reflection, or somehow with the dynamic keyword?

Upvotes: 1

Views: 238

Answers (2)

Clement
Clement

Reputation: 4307

  1. Add the Spring.Core NuGet package
  2. Use the ExpressionEvaluator class (see http://www.springframework.net/doc/reference/html/expressions.html)

Examples:

ExpressionEvaluator.GetValue("Test", "Length.ToString().Length");
ExpressionEvaluator.GetValue(null, "DateTime.Now")

Upvotes: 0

Primary Key
Primary Key

Reputation: 1237

You can't do it either with reflection or with dynamic keyword. What you can do is:

  1. parse the string in order to create an lambda expression tree that will be compiled and executed against your parameter(s)
  2. use CodeDOM
  3. use some dynamic language like IronRuby or IronPython

Upvotes: 2

Related Questions