C # rewrite tostring Method for programming

Source: Internet
Author: User

Every object in C # inherits the tostring method. This method returns the string representation of the object. For example, all int-type variables have a tostring method, which allows these variables to return their content as a string:

 
IntX = 42;
 
StringStrx = x. tostring ();
System. Console. writeline (strx );

When creating a custom class or structure, you should override the tostring methodCodeProvides type information.

When you decide the type of information provided through this method, consider whether your class or structure will be used by untrusted code. Make sure that you do not provide any information that will be exploited by malicious code.

Override the onstring method in the class or structure 1. Declare the tostring method through the modifier and return type below:
Public Override StringTostring (){}

2. implement this method to return a string.

The following example not only returns the class name, but also the data of an instance specific to the class. Note that it will also use the tostring method on the age variable to convert int to an output string.

ClassPerson
 
{
StringName;
 
IntAge;
Sampleobject (StringName,IntAge)
 
{
This. Name = Name;
 
This. Age = age;
}
 
Public Override StringTostring ()
{
 
StringS = age. tostring ();
Return "Person :"+ Name +""+ S;
 
}
}

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.