Accessing Expression.DebugView from code

c# expression-trees

Question

I'm creating an expression tree manually like this

var innerAddition = Expression.Add(Expression.Constant(5), Expression.Constant(9));
var mult = Expression.Multiply(innerAddition, Expression.Constant(2));
var top = Expression.Add(Expression.Constant(3), mult);

When I look at DebugView in debug mode, I see 3 + (5 + 9) * 2, which is what I would like to output from my program. I understand this is using the expression tree visualizer. Is there a way to use this from my code? Thanks!

Accepted Answer

The classes that implement the debug view features are intentionally internal so that you cannot access them without reflection. Although this seems unfair, the purpose of debugging is debugging and it is not intended as a supported API and therefore could change at any time, perhaps to improve debugging! Using the supported public APIs will ensure compatibility with future versions.

Here is another StackOverflow question using the public APIs:


Popular Answer

Here is a simple extension method to get the internal property's value using reflection.

public static string GetDebugView(this Expression exp)
{
    if (exp == null)
        return null;

    var propertyInfo = typeof(Expression).GetProperty("DebugView", BindingFlags.Instance | BindingFlags.NonPublic);
    return propertyInfo.GetValue(exp) as string;
}



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why