[C # Programming Guide] Overriding the ToString method

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.