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