Search code examples
c#tostringreadabilitymaintainability

Best practices: a Property, a Function or ToString?


I am trying to determine a best practice when writing code to get the string representation of a custom class.

Imagine we have the following:

public class DoubleParameter
{
    public double Value { get; set; }
    public string Description { get; set; }
    public string Units { get; set; }
}

And we want the ability to get a string representation of the class for debugging purposes. Regarding code readability/maintainability and best practices, I'm evaluating three options

  1. An Inline Property
  2. A Custom Method
  3. Overriding ToString()

Most of these are very similar from the compiler's point of view - but are there any objective reasons to prefer any particular option in terms of readability/maintainability? Or is it a matter of personal preference?

Examples of use:

// Option 1 - Inline Property
public string ReadableValue => 
    $"{this.Description} => {this.Value.ToString("F2")} ({this.Units})";
// example usage: Console.WriteLine(myVar.ReadableValue);

// Option 2 - Custom Method
public string ToReadable() =>
    $"{this.Description} => {this.Value.ToString("F2")} ({this.Units})";
// example usage: Console.WriteLine(myVar.ToReadable());

// Option 3 - Overriding ToString()
public override string ToString() =>
    $"{this.Description} => {this.Value.ToString("F2")} ({this.Units})";
// example usage: Console.WriteLine(myVar);

Solution

  • For debugging purposes, ToString() wins hands down.

    Why? Because when you're stepping through code using VisualStudio, VS will easily display the ToString() results when you hover over a variable, or put the variable in the watch window. Otherwise, you have to dig in to get the property you're concerned with. This can be especially annoying if you're working with lists/enumerations/etc.

    Also, ToString() already exists, and is already supposed to be the text representation of an instance of your object. That's the whole point of it. Why add another property that's also the string representation of your object?