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

Any way to make properties of an object to appear in a particular order when inspecting in VS?


I have a legacy project where I can often see model classes that have up to 100 properties and while debugging I'd like to see them in a particular order as it's an ordered sequence of data. Is there any sort of an attribute that can make Visual Studio debugger to display them in a particular order instead of sorting them by names?


Solution

  • You can use DebuggerDisplayAttribute class to customise debugger description. Please read about it in MSDN.

    If you append that attribute to certain class you can define how you want to see description during debugging.

    One example from MSDN. Here value and key are will be more visible during debugging:

    [DebuggerDisplay("{value}", Name = "{key}")]
    internal class KeyValuePairs
    {
        private IDictionary dictionary;
        private object key;
        private object value;
    
        public KeyValuePairs(IDictionary dictionary, object key, object value)
        {
            this.value = value;
            this.key = key;
            this.dictionary = dictionary;
        }
    }
    

    Here will be easier to see value and key during debugging.

    You can consider DebuggerBrowsableAttribute which determine what will debugger display certain members. You can even hide some members.

    Here is some example of DebuggerBrowsableAttribute:

    public class User
    {
        [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
        public string Login { get; set; }
    
        [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
        public FullName Name { get; set; }
    
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        public string HashedPassword { get; set; }
    }
    

    As you see property HashedPassword will be hidden from debugging.

    Also, you can use Watch window in Visual Studio and configure your variable which you want to track.