Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a delegate other than ToString to show an object's value while debugging?

.NET/Visual Studio uses an object's ToString() method to display the value of an object when viewing it in the debugger. I would like to display specific information, but since .ToString() is often used by the framework when converting an object to a string, I cannot do it by overriding ToString(). Is there an attribute I can use to tell the debugger to use a different method or property?

like image 573
Daniel Schaffer Avatar asked Mar 28 '12 19:03

Daniel Schaffer


People also ask

Why should you override the ToString () method?

When you create a custom class or struct, you should override the ToString method in order to provide information about your type to client code. For information about how to use format strings and other types of custom formatting with the ToString method, see Formatting Types.

How do you override a ToString method in C#?

Override ToString() Method in C# NET inherit from the “System. Object” class. Let us say when we create a class and if we see the object of the class there are four methods present in each object. These are are GetType(), ToString(), GethashCode(), Equals().

How do I debug COM objects in Visual Studio?

In visual studio if you open tools >> Options and then debugging >> General make sure the option "Use managed compatibility mode" it checked on. This should show com objects as their proper types in the debugger.

What does ToString () do in C#?

ToString is the major formatting method in the . NET Framework. It converts an object to its string representation so that it is suitable for display.


1 Answers

Use the DebuggerDisplayAttribute[MSDN]. You supply it with a format string that references fields/properties within the class to display while debugging without having to mess with ToString().

[DebuggerDisplay("Count = {count}")]
class MyHashtable
{
    public int count = 4;
}

It also works with methods:

[DebuggerDisplay("{ToDebugString()}")]
public class SomeClass
{
    public override String ToString()
    {
        return "Normal ToString()";
    }

    public String ToDebugString()
    {
        return "ToDebugString()";
    }
 }
like image 55
FishBasketGordo Avatar answered Oct 21 '22 19:10

FishBasketGordo