How To: Override the ToString Method
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

How To: Override the ToString Method (C# Programming Guide)

Every object in C# inherits the ToString method, which returns a string representation of that object. For example, all variables of type int have a ToString method, allowing them to return their contents as a string:

int x = 42;
string strx = x.ToString();

When you create a custom class or struct, you should override the ToString method in order to provide information about your type to client code.

Security noteSecurity Note

When deciding what information to provide through this method, consider whether your class or struct will ever be used by untrusted code. Be careful to ensure that you do not provide any information that could be exploited by malicious code.

To override the OnString method in your class or struct:

  1. Declare a ToString method with the following modifiers and return type:

    public override string ToString(){}
  2. Implement the method so that it returns a string.

    The following example returns not only the name of the class, but also the data specific to a particular instance of the class. Note that it also uses the ToString method on the age variable to covert the int to a string that can be output.

    class Person
      string name;
      int age;
      SampleObject(string name, int age)
      { = name;
      this.age = age;
      public override string ToString() 
         string s = age.ToString();
         return "Person: " + name + " " + s;

See Also

© 2015 Microsoft