Share via


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);

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 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);
    

See Also

Concepts

C# Programming Guide

Reference

Classes and Structs (C# Programming Guide)

new (C# Reference)

override (C# Reference)

virtual (C# Reference)

Change History

Date

History

Reason

October 2008

Revised and updated code example.

Content bug fix.