Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

Object.ToString Method

Returns a string that represents the current object.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

'Declaration
Public Overridable Function ToString As String

Return Value

Type: System.String
A string that represents the current object.

Object.ToString is the major formatting method in the .NET Framework. It converts an object to its string representation so that it is suitable for display. (For information about formatting support in the .NET Framework, see Formatting Types in the .NET Framework.) Default implementations of the Object.ToString method return the fully qualified name of the object's type.

Important noteImportant

You may have reached this page by following the link from the member list of another type. That is because that type does not override Object.ToString. Instead, it inherits the functionality of the Object.ToString method.

Types frequently override the Object.ToString method to provide a more suitable string representation of a particular type. Types also frequently overload the Object.ToString method to provide support for format strings or culture-sensitive formatting.

In this section:

The default Object.ToString() method
Overriding the Object.ToString() method
Overloading the ToString method
Extending the Object.ToString method
Notes for the Windows Runtime

The default Object.ToString() method

The default implementation of the ToString method returns the fully qualified name of the type of the Object, as the following example shows.

Module Example
   Public Sub Main()
      Dim obj As New Object()
      Console.WriteLine(obj.ToString())
   End Sub 
End Module 
' The example displays the following output: 
'      System.Object

Because Object is the base class of all reference types in the .NET Framework, this behavior is inherited by reference types that do not override the ToString method. The following example illustrates this. It defines a class named Object1 that accepts the default implementation of all Object members. Its ToString method returns the object's fully qualified type name.

Imports Examples

Namespace Examples
   Public Class Object1
   End Class 
End Namespace 

Module Example
   Public Sub Main()
      Dim obj1 As New Object1()
      Console.WriteLine(obj1.ToString())
   End Sub 
End Module 
' The example displays the following output: 
'   Examples.Object1

Overriding the Object.ToString() method

Types commonly override the Object.ToString method to return a string that represents the object instance. For example, the base types such as Char, Int32, and String provide ToString implementations that return the string form of the value that the object represents. The following example defines a class, Object2, that overrides the ToString method to return the type name along with its value.

Public Class Object2
   Private value As Object 

   Public Sub New(value As Object)
      Me.value = value
   End Sub 

   Public Overrides Function ToString() As String 
      Return MyBase.ToString + ": " + value.ToString()
   End Function 
End Class 

Module Example
   Public Sub Main()
      Dim obj2 As New Object2("a"c)
      Console.WriteLine(obj2.ToString())
   End Sub 
End Module 
' The example displays the following output: 
'       Object2: a

The following table lists the type categories in the .NET Framework and indicates whether or not they override the Object.ToString method.

Type category

Overrides Object.ToString()

Behavior

Class

n/a

n/a

Structure

Yes (ValueType.ToString)

Same as Object.ToString()

Enumeration

Yes (Enum.ToString)

The member name

Interface

No

n/a

Delegate

No

n/a

See the Notes to Inheritors section for additional information on overriding ToString.

Overloading the ToString method

In addition to overriding the parameterless Object.ToString method, many types overload the ToString method to provide versions of the method that accept parameters. Most commonly, this is done to provide support for variable formatting and culture-sensitive formatting.

The following example overloads the ToString method to return a result string that includes the value of various fields of an Automobile class. It defines four format strings: G, which returns the model name and year; D, which returns the model name, year, and number of doors; C, which returns the model name, year, and number of cylinders; and A, which returns a string with all four field values.

Public Class Automobile
   Private _doors As Integer 
   Private _cylinders As String 
   Private _year As Integer 
   Private _model As String 

   Public Sub New(model As String, year As Integer, doors As Integer,
                  cylinders As String)
      _model = model
      _year = year
      _doors = doors
      _cylinders = cylinders
   End Sub 

   Public ReadOnly Property Doors As Integer 
      Get 
          Return _doors
      End Get 
   End Property 

   Public ReadOnly Property Model As String 
      Get 
         Return _model
      End Get 
   End Property 

   Public ReadOnly Property Year As Integer 
      Get 
         Return _year
      End Get 
   End Property 

   Public ReadOnly Property Cylinders As String 
      Get 
         Return _cylinders
      End Get 
   End Property 

   Public Overrides Function ToString() As String 
      Return ToString("G")
   End Function 

   Public Overloads Function ToString(fmt As String) As String 
      If String.IsNullOrEmpty(fmt) Then fmt = "G" 

      Select Case fmt.ToUpperInvariant()
         Case "G" 
            Return String.Format("{0} {1}", _year, _model)
         Case "D" 
            Return String.Format("{0} {1}, {2} dr.",
                                 _year, _model, _doors)
         Case "C" 
            Return String.Format("{0} {1}, {2}",
                                 _year, _model, _cylinders)
         Case "A" 
            Return String.Format("{0} {1}, {2} dr. {3}",
                                 _year, _model, _doors, _cylinders)
         Case Else 
            Dim msg As String = String.Format("'{0}' is an invalid format string",
                                              fmt)
            Throw New ArgumentException(msg)
      End Select 
   End Function 
End Class 

Module Example
   Public Sub Main()
      Dim auto As New Automobile("Lynx", 2016, 4, "V8")
      Console.WriteLine(auto.ToString())
      Console.WriteLine(auto.ToString("A"))
   End Sub 
End Module 
' The example displays the following output: 
'       2016 Lynx 
'       2016 Lynx, 4 dr. V8

The following example calls the overloaded Decimal.ToString(String, IFormatProvider) method to display culture-sensitive formatting of a currency value.

Imports System.Globalization

Module Example
   Public Sub Main()
      Dim cultureNames() As String = { "en-US", "en-GB", "fr-FR",
                                       "hr-HR", "ja-JP" }
      Dim value As Decimal = 1603.49d
      For Each cultureName In cultureNames
         Dim culture As New CultureInfo(cultureName)
         Console.WriteLine("{0}: {1}", culture.Name,
                           value.ToString("C2", culture))
      Next 
   End Sub 
End Module 
' The example displays the following output: 
'       en-US: $1,603.49 
'       en-GB: £1,603.49 
'       fr-FR: 1 603,49 € 
'       hr-HR: 1.603,49 kn 
'       ja-JP: ¥1,603.49

For more information on format strings and culture-sensitive formatting, see Formatting Types in the .NET Framework. For the format strings supported by numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. For the format strings supported by date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.

Extending the Object.ToString method

Because a type inherits the default Object.ToString method, you may find its behavior undesirable and want to change it. This is particularly true of arrays and collection classes. While you may expect the ToString method of an array or collection class to display the values of its members, it instead displays the type fully qualified type name, as the following example shows.

Imports System.Collections.Generic

Module Example
   Public Sub Main()
      Dim values() As Integer = { 1, 2, 4, 8, 16, 32, 64, 128 }
      Console.WriteLine(values.ToString())

      Dim list As New List(Of Integer)(values)
      Console.WriteLine(list.ToString())
   End Sub 
End Module 
' The example displays the following output: 
'    System.Int32[] 
'    System.Collections.Generic.List`1[System.Int32]

You have several options to produce the result string that you'd like.

  • If the type is an array, a collection object, or an object that implements the IEnumerable or IEnumerable(Of T) interfaces, you can enumerate its elements by using the foreach statement in C# or the For Each...Next construct in Visual Basic.

  • If the class is not sealed (in C#) or NotInheritable (in Visual Basic), you can develop a wrapper class that inherits from the base class whose Object.ToString method you want to customize. At a minimum, this requires that you do the following:

    1. Implement any necessary constructors. Derived classes do not inherit their base class constructors.

    2. Override the Object.ToString method to return the result string that you'd like.

    The following example defines a wrapper class for the List(Of T) class. It overrides the Object.ToString method to display the value of each method of the collection rather than the fully qualified type name.

    Imports System.Collections.Generic
    
    Public Class CList(Of T) : Inherits List(Of T)
       Public Sub New(capacity As Integer)
          MyBase.New(capacity)
       End Sub 
    
       Public Sub New(collection As IEnumerable(Of T))
          MyBase.New(collection)
       End Sub 
    
       Public Sub New()
          MyBase.New()
       End Sub 
    
       Public Overrides Function ToString() As String 
          Dim retVal As String = String.Empty
          For Each item As T In Me 
             If String.IsNullOrEmpty(retval) Then
                retVal += item.ToString()
             Else
                retval += String.Format(", {0}", item)
             End If 
          Next 
          Return retVal
       End Function 
    End Class 
    
    Module Example
       Public Sub Main()
          Dim list2 As New CList(Of Integer)
          list2.Add(1000)
          list2.Add(2000)
          Console.WriteLine(list2.ToString())
       End Sub 
    End Module 
    ' The example displays the following output: 
    '       1000, 2000
    
  • Develop an extension method that returns the result string that you want. Note that you can't override the default Object.ToString method in this way (that is, your extension class (in C#) or module (in Visual Basic) cannot have a parameterless method named ToString that is called in place of the original type's ToString method. You'll have to provide some other name for your parameterless ToString replacement.

    The following example defines two methods that extend the List(Of T) class: a parameterless ToString2 method, and a ToString method with a String parameter that represents a format string.

    Imports System.Collections.Generic
    Imports System.Runtime.CompilerServices
    
    Public Module StringExtensions
       <Extension()>
       Public Function ToString2(Of T)(l As List(Of T)) As String 
          Dim retVal As String = "" 
          For Each item As T In l
             retVal += String.Format("{0}{1}", If(String.IsNullOrEmpty(retVal),
                                                         "", ", "),
                                      item)
          Next 
          Return If(String.IsNullOrEmpty(retVal), "{}", "{ " + retVal + " }")
       End Function
    
       <Extension()>
       Public Function ToString(Of T)(l As List(Of T), fmt As String) As String 
          Dim retVal As String = String.Empty
          For Each item In l
             Dim ifmt As IFormattable = TryCast(item, IFormattable)
             If ifmt IsNot Nothing Then
                retVal += String.Format("{0}{1}",
                                        If(String.IsNullOrEmpty(retval),
                                           "", ", "), ifmt.ToString(fmt, Nothing))
             Else
                retVal += ToString2(l)
             End If 
          Next 
          Return If(String.IsNullOrEmpty(retVal), "{}", "{ " + retVal + " }")
       End Function 
    End Module 
    
    Module Example
       Public Sub Main()
          Dim list As New List(Of Integer)
          list.Add(1000)
          list.Add(2000)
          Console.WriteLine(list.ToString2())
          Console.WriteLine(list.ToString("N0"))
       End Sub 
    End Module 
    ' The example displays the following output: 
    '       { 1000, 2000 } 
    '       { 1,000, 2,000 }
    

Notes for the Windows Runtime

When you call the ToString method on a class in the Windows Runtime, it provides the default behavior for classes that don’t override ToString. This is part of the support that the .NET Framework provides for the Windows Runtime (see .NET Framework Support for Windows Store Apps and Windows Runtime). Classes in the Windows Runtime don’t inherit Object, and don’t always implement a ToString. However, they always appear to have ToString, Equals(Object), and GetHashCode methods when you use them in your C# or Visual Basic code, and the .NET Framework provides a default behavior for these methods.

Starting with the .NET Framework 4.5.1, the common language runtime will use IStringable.ToString on a Windows Runtime object before falling back to the default implementation of Object.ToString.

NoteNote

Windows Runtime classes that are written in C# or Visual Basic can override the ToString method.

Starting with Windows 8.1, the Windows Runtime includes an IStringable interface whose single method, IStringable.ToString, provides basic formatting support comparable to that provided by Object.ToString. To prevent ambiguity, you should not implement IStringable on managed types.

When managed objects are called by native code or by code written in languages such as JavaScript or C++/CX, they appear to implement IStringable. The common language runtime will automatically route calls from IStringable.ToString to Object.ToString in the event IStringable is not implemented on the managed object.

Caution noteCaution

Because the common language runtime auto-implements IStringable for all managed types in Windows Store apps, we recommend that you do not provide your own IStringable implementation. Implementing IStringable may result in unintended behavior when calling ToString from the Windows Runtime, C++/CX, or JavaScript.

If you do choose to implement IStringable in a public managed type that is exported in a Windows Runtime component, the following restrictions apply:

  • You can define the IStringable interface only in a "class implements" relationship, such as

    public class NewClass : IStringable
    

    in C#, or

    Public Class NewClass : Implements IStringable
    

    in Visual Basic.

  • You cannot implement IStringable on an interface.

  • You cannot declare a parameter to be of type IStringable.

  • IStringable cannot be the return type of a method, property, or field.

  • You cannot hide your IStringable implementation from base classes by using a method definition such as the following:

    public class NewClass : IStringable
    {
       public new string ToString()
       {
          return "New ToString in NewClass";
       }
    }
    

    Instead, the IStringable.ToString implementation must always override the base class implementation. You can hide a ToString implementation only by invoking it on a strongly typed class instance.

Note that under a variety of conditions, calls from native code to a managed type that implements IStringable or hides its ToString implementation can produce unexpected behavior.

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 IFormattable.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 String.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.

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

XNA Framework

Supported in: 3.0, 2.0, 1.0

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8

Portable Class Library

Supported in: Portable Class Library
Show:
© 2015 Microsoft