Question

Does String.Format run ToString?

For example, if I have an object of a "complex" class, can I do:

 <i>String.Format("String rep. {0}",complexObj);</i>
Was it helpful?

Solution

From the documentation:

How arguments are formatted:

Format items are processed sequentially from the beginning of the string. Each format item has an index that corresponds to an object in the method's argument list. The Format method retrieves the argument and derives its string representation as follows:

  • If the argument is null, the method inserts String.Empty into the result string.
  • If you call the Format(IFormatProvider, String, Object[]) overload and the provider parameter implements the ICustomFormatter interface, the argument is passed to the provider object's ICustomFormatter.Format(String, Object, IFormatProvider) method. If the format item includes a formatString argument, it is passed as the first argument to the method. If the ICustomFormatter implementation is able to provide formatting services, it returns the string representation of the argument; otherwise, it returns null and the next step executes.
  • If the argument implements the IFormattable interface, its IFormattable.ToString implementation is called.
  • The argument's parameterless ToString method, which is either overridden or inherited from the Object class, is called.

So yes, finally - as a fallback - the ToString method is called.

OTHER TIPS

All objects inherit from System.Object which has a ToString() method which will be used if you do not override it. If you want a more meaningful output, you should override it.

public override string ToString()
{
    return "<Insert your output here>"
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top