Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to automatically override ToString() on a class?

Tags:

c#

.net

I find it useful to override ToString() on many of the simple DTO/POCO classes I write to show some good information when hovering over instances within the debugger.

Here is one example:

  public class IdValue< T >
  {
    public IdValue( int id, T value )
    {
      Id = id;
      Value = value;
    }

    public int Id { get; private set; }
    public T Value { get; private set; }

    public override string ToString()
    {
      return string.Format( "Id: {0} Value: {1}", Id, Value );
    }
  }

Is there a way in .NET to automatically have a ToString() override that lists out public properties or is there a good convention to follow?

like image 597
Rob Packwood Avatar asked Feb 26 '10 17:02

Rob Packwood


2 Answers

You could override ToString in a base class then use reflection on the instance to discover the public properties of the derived class. But this will likely introduce performance problems in other areas of your code. Additionally, because ToString is used by a lot of things (String.Format, default data binding, etc.) overriding ToString for debugging purposes will make your classes less useful in other scenarios.

Instead, you may want to use the DebuggerDisplay attribute to control how the debugger shows hover tips and info in the watch window and such. I'm pretty sure this works if you apply it to a base class. You can also create custom visualizers but that's more involved. Check out this link for more info on enhancing the debugger display experience.

Enhancing Debugging

like image 142
Josh Avatar answered Sep 25 '22 15:09

Josh


If you don't mind an external dependency, you could turn to a framework helping with printing all of your objects properties like StatePrinter

An example usage

class AClassWithToString
{
  string B = "hello";
  int[] C = {5,4,3,2,1};

  // Nice stuff ahead!
  static readonly StatePrinter printer = new StatePrinter();
  public override string ToString()
  {
    return printer.PrintObject(this);
  }
}
like image 28
Carlo V. Dango Avatar answered Sep 23 '22 15:09

Carlo V. Dango