Each class or struct in C # implicitly inherits the Object class. Therefore, each object in C # Gets the ToString method, which returns the string representation of the object . For example, all variables of type int have a ToString method, which allows these variables to return their contents as strings:
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 to provide the type information to the client code.
Overriding the ToString method in a class or struct
1. Declare the ToString method with the following modifier 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 and data that is specific to an instance of the class.
class Person
{
Public string Name {get; set;}
Public int Age {get; set;}
Public Override string ToString ()
{
return "Person:" "" + age;
}
}
Test the ToString method, as shown in the following code example:
New "John", age = 12};
Console.WriteLine (person);
Output:
Person:john 12
[C # Programming Guide] Overriding the ToString method