[Journal - Implementing ToString]

Implementing ToString

Monday, September 4, 2006

The ToString() method can be used for several purposes, as practice proves. In the case of using it for diagnostic purposes, as is the original purpose, you'd typically want to look at all of an object's properties.

The Gregor.Core.Conv module offers the ThisToString function, which reflectively converts an object's data to a string:

public override string ToString(){
    return Conv.ThisToString(this, ToStringOptions.Default);
}

There are a number of options available:

[Flags()]
public enum ToStringOptions {
    None         = 0x0,
    FullTypeName = 0x1,
    Properties   = 0x2,
    Fields       = 0x4,
    Default      = ToStringOptions.Properties
}

Bonus: if a property is added to the class, a base class, or even a derived class, the information returned by ToString() is updated automatically. Note that a second overload to ThisToString allows passing member names as a param array, which serve as a filter in case you don't want to output all fields or properties.