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
- An Inline Property
- A Custom Method
- 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);