Search code examples
c#reflectionexpression-trees

How to evaluate a simple C# string


I have been reading up Expression trees, and I think this is a good example to use them, still I can't seem to grasp how this would be done.

I have a set of strings that I want evaluated, they are all of the type:

exp == exp , or exp != exp , or exp (<,>,>=,<=) exp if exp is Numerical Type.

The exp do not need to check if they are valid I am fine with them blowing up if they are not.

My issue is, how to I parse to get the actual obj.

I want to pass a string like these below

Owner.Property.Field == 3;

or

Owner.Field == 3;

or 

Owner.Method(1) == true

And get if the evaluation is true or not. MY issue is how do I travel down the "path" on the left and get the value?

I implemented a version with Reflection and string parsing, that somehow does the work - except for when we are using a method, and honestly its not that performant at all. I want this to be as performant as possible can get, and if possible give me a small explanation of how the expression works , so I can learn.


Solution

  • You can use code generation libraries like CodeDOM or Roslyn to generate Func that will do the evaluation.

    For example, in Roslyn you can create a Session and set an object containing Owner as the Host object of the Session. than you can generate the code in the Session as you wish like the following:

    Session session = ScriptEngine.CreateSession(objectContainingOwnerAsProperty);
    bool result = session.Execute<bool>("Owner.Field == 8");
    

    Now result will contain the evaluation result for your string without reflection nor string analysis.