The difference between ToString (), Convert.ToString (), (string), as String

Source: Internet
Author: User

There are usually four ways of object to string (assuming there is an object obj): obj. ToString (), Convert.ToString (), (string) obj, obj as String. They can all convert object objects into string objects. I'll talk about their similarities and differences and which ones should be used in practice.

The first two methods are usually the string objects that are obtained by other objects, and the difference between them is that only the table is now null for the object to be converted, and obj is called if obj is null. The ToString method causes a NullReferenceException exception, and calling Convert.ToString does not throw an exception and returns a null.

Using cast (string) obj requires that the run-time type of obj must be string. If not, an exception is thrown.

The As method is relatively smooth, and when Obj's run-time type is not a string, it returns null without throwing an exception.

So in the usual case where we need to get a string representation of an object, we should use ToString and convert.tostring, and then you have to choose one according to the situation, if you can guarantee that your object is not NULL, then two is the same. If it is possible to NULL, you should use convert.tostring, if you want it to be null when throwing an exception, then of course you can choose ToString.

Editor's note:

Here is the object to string, if the first ToString () is called on other types, the actual content may be the description of the class, depending on how the class implements the ToString () method.

The difference between ToString (), Convert.ToString (), (string), as String

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.