Getting to Expression. DebugView from the source code

c# expression-trees


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!

5/14/2011 3:42:58 AM

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:

5/23/2017 12:19:23 PM

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;

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow