Compartir a través de


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

Every class or struct in C# implicitly inherits the Object class. Therefore, every object in C# gets the ToString method, which returns a string representation of that object. For example, all variables of type int have a ToString method, which enables them to return their contents as a string:

int x = 42;
string strx = x.ToString();
Console.WriteLine(strx);
// Output: 
// 42

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.

For information about how to use format strings and other types of custom formatting with the ToString method, see Formatting Types.

Security noteSecurity Note

When you decide 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 ToString 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 the name of the class in addition to the data specific to a particular instance of the class.

    class Person
        {
            public string Name { get; set; }
            public int Age { get; set; }
    
            public override string ToString()
            {
                return "Person: " + Name + " " + Age;
            }
        }
    

    You can test the ToString method as shown in the following code example:

    Person person = new Person { Name = "John", Age = 12 };
    Console.WriteLine(person);
    // Output: 
    // Person: John 12
    

See Also

Reference

Classes and Structs (C# Programming Guide)

string (C# Reference)

new (C# Reference)

override (C# Reference)

virtual (C# Reference)

IFormattable

Concepts

C# Programming Guide

Other Resources

Strings (C# Programming Guide)

Formatting Types