|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.|
How to: Override the ToString Method (C# Programming Guide)
Updated: October 2008
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:
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.
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
Declare a ToString method with the following modifiers and return type:
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.
You can test the ToString method as shown in the following code example: