Export (0) Print
Expand All

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();
System.Console.WriteLine(strx);

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)
      {
      this.name = name;
      this.age = age;
      }
      public override string ToString() 
      {
         string s = age.ToString();
         return "Person: " + name + " " + s;
      }
    }
    

See Also

Community Additions

ADD
Show:
© 2014 Microsoft