Search code examples
c#.netvisual-studiodebuggingvisual-studio-debugging

Control the way .NET BCL types are shown in the debugger (interested in KeyValuePair(TKey, TValue) )


There's a question here regarding the overriding of ToString() in KeyValuePair(TKey, TValue), which it's not possible.

I saw there are some attribute types like DebuggerDisplayAttribute, DebuggerTypeProxyAttribute which can control the way a type is displayed in the debugger. I only used debugger visualizers.

Logically, these attributes can only be applied to user-defined classes (except for partial classes I think).

So is there any way to control the debugging result of a built-in (BCL) .NET type in Visual Studio?

EDIT: To make it a little bit clearer, I'm mainly interested in the string representation of the type. It's sort of 'overriding' ToString() just for debugging.


Solution

  • Some time ago I wrote a post about reading SQL exception dumps where I used the visualizer for System.Data.SqlClient.SqlParameter). You may read the whole post for a working example but in your case following steps are required:

    In folder C:\Users\<your login>\Documents\<your Visual Studio version>\Visualizers there is a special file named autoexp.cs which stores your local visualizer settings (defined using DebuggerDisplayAttribute). If you can’t find this file you can safely copy it from <Visual Studio installation folder>\Common7\Packages\Debugger\Visualizers\Original\. You can then append a new rule by the end of this file:

    [assembly: DebuggerDisplay(@"\{MyKey = {Key}\}", Target = typeof(System.Collections.Generic.KeyValuePair<,>))]
    

    Finally you need to recompile the file:

    csc /t:library autoexp.cs
    

    and restart Visual Studio. You new string representation of the KeyValuePair should appear in VS debugger.