Objective C # Item 5: provides a meaningful tostring Function

Source: Internet
Author: User

When writing a custom type, the system automatically provides the tostring function even if we do not write the tostring function. For example:

Public class clsuserinfo

{

Private string strusername;

......

}

 

However, the tostring function provided by the system does not do much and cannot reflect some attributes of the current object. The above code is used, the result returned by calling tostring is the same as that returned by GetType and converted to string. The returned value does not have much meaning for the caller.

 

To provide a meaningful tostring function, you need to overload the tostring function to implement a tostring function targeting this object. For example, for the preceding clsuserinfo type, the following method makes the tostring function more meaningful.

Public class clsuserinfo

{

Private string strusername;

......

Public override string tostring ()

{

Return string. Format ("User name: {0}", strusername );

}

}

 

Provide a meaningful tostringFunctions are useful for debugging or publishing such a feature, because this method is the easiest way to combine strings with the member attributes of the feature class.. However, when writing code, people, including me, often ignore providing a meaningful tostring function, which seems to be improved in future coding.

 

In addition to the tostring function provided by the overload system, you can inherit the iformattable interface in C # To provide more complex tostring functions. In this respect, I don't want to say much about it because it inherits the interface, the provided tostring function may have many changes, which may be more profound to the real application.

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.