Object.ToString Method

Definition

Returns a string that represents the current object.

public:
 virtual System::String ^ ToString();
public virtual string ToString ();
public virtual string? ToString ();
abstract member ToString : unit -> string
override this.ToString : unit -> string
Public Overridable Function ToString () As String

Returns

A string that represents the current object.

Remarks

For more information about this API, see Supplemental API remarks for Object.ToString.

Notes to Inheritors

When you implement your own types, you should override the ToString() method to return values that are meaningful for those types. Derived classes that require more control over formatting than ToString() provides can implement the IFormattable interface. Its ToString(String, IFormatProvider) method enables you to define format strings that control formatting and to use an IFormatProvider object that can provide for culture-specific formatting.

Overrides of the ToString() method should follow these guidelines:

  • The returned string should be friendly and readable by humans.

  • The returned string should uniquely identify the value of the object instance.

  • The returned string should be as short as possible so that it is suitable for display by a debugger.

  • Your ToString() override should not return Empty or a null string.

  • Your ToString() override should not throw an exception.

  • If the string representation of an instance is culture-sensitive or can be formatted in multiple ways, implement the IFormattable interface.

  • If the returned string includes sensitive information, you should first demand an appropriate permission. If the demand succeeds, you can return the sensitive information; otherwise, you should return a string that excludes the sensitive information.

  • Your ToString() override should have no observable side effects to avoid complications in debugging. For example, a call to the ToString() method should not change the value of instance fields.

  • If your type implements a parsing method (or Parse or TryParse method, a constructor, or some other static method that instantiates an instance of the type from a string), you should ensure that the string returned by the ToString() method can be converted to an object instance.

Applies to

See also