Search code examples
c#visual-studiodebuggervisualizer

How to use Visual Studio Text Visualizer for custom types?


In Visual Studio 2015 (and in some older versions) when debugging C# code it's possible to display the values of the string variables in various visualizers (Text, XML, HTML, JSON) via a drop-down list with a magnifying glass icon. This also works for some non-string types, for example, System.Xml.Linq.XElement. Is it possible to use these build-in visualizers to display the value of a variable of my own custom type?

Context:

I need to be able to quickly check the state of a complicated custom type that can be acceptably visualized only in a multi-line text environment.


Solution

  • If I understand your question correctly, then you can achieve what you're after with a DebuggerTypeProxy. It causes the debugger to create and display a proxy object whenever you're inspecting objects of your complex type.

    In the example below the proxy object contains a (multi-line) string property that you can view with the text visualizer. If you still need to look at the underlying object itself, then that's what the Raw view button is for.

    [DebuggerTypeProxy(typeof(ComplexTypeProxy))]
    class ComplexType
    {
        // complex state
    }
    
    class ComplexTypeProxy
    {
        public string Display
        {
            get { return "Create a multi-line representation of _content's complex state here."; }
        }
    
        private ComplexType _content;
    
        public ComplexTypeProxy(ComplexType content)
        {
            _content = content;
        }
    }