Search code examples
c#.netlinqexpression-trees

Get type of System.Linq.Expressions.Expression object


In my program I have a list of System.Linq.Expressions.Expression objects. This list can include different types of a specific Expression. For example BinaryExpression, ConditionalExpression etc. (see https://msdn.microsoft.com/en-us/library/system.linq.expressions.expression(v=vs.110).aspx). When reading this list I want to check which specific type of Expression it is (BinaryExpression, ConditinalExpression, etc.).

How do I get the name/type of the derived Expression class?

UPDATE

Here the definition of the list of expressions:

IEnumerable<Expression<Func<T, object>>> Expressions { get; }

and the code to get the expressions:

foreach (var expression in test.Expressions)
{
    var test = expression.GetType().ToString(); //System.Linq.Expressions.Expression`1[System.Func`2[TestObject,System.Object]]
}

Solution

  • You must

    expression.Body.GetType();
    

    What you were looking at is the Expression<Func<,>>, what you are interested in is its .Body.