ToString () outputs an object

Source: Internet
Author: User

namespaceconsoleapplication1{classA {intAge= -; stringName="South elder brother";  Public Override stringToString () {//return (name + age);//these two lines of code are equivalent            return("name="+name+"age="+Age ); }    }    classProgram {Static voidMain (string[] args) {A obj=NewA (); Console.WriteLine (obj);//these two lines of code are equivalent, with the sameConsole.WriteLine (obj.            ToString ());                    Console.read (); }    }}


After removing the override, the output is as follows:
will have as followsThe warning is generated, but can be run.

When an object needs to be output to a monitor, it is often necessary to call its ToString () method to convert the object's contents to a string. All classes in C # have a default ToString () method, and you need to override the ToString () method yourself if you need special conversion functionality. There are two points to note when declaring the ToString method: it must be declared as a public type, the return type should be string, the name of the method must be ToString, and there is no parameter; the output method Console.Write () is not used in the method body;

ToString () outputs an object

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.