Tostring (), convert. tostring (), (string), as string differences

Source: Internet
Author: User

Generally, there are four methods for object to string (assuming object OBJ): obj. tostring (), convert. tostring (), (string) OBJ, and OBJ as string. They can all convert object objects to string objects. Let me talk about their similarities and differences and what they should be used in practice.

The first two methods are generally string objects obtained from other objects. The difference between them is only that when the object to be converted is null, if obj is null, obj is called. the tostring method causes nullreferenceexception and calls convert. tostring does not throw an exception and returns a null value.

Forced conversion (string) OBJ requires that the runtime type of OBJ must be string. If not, an exception is thrown.

The AS method is relatively stable. If the runtime type of obj is not string, null is returned without throwing an exception.

Therefore, when we need to get the string expression of an object, we should use tostring and convert. tostring. At this time, you have to select one based on the situation. If you can ensure that your object is not null, then the two are similar. If it is possible to be null, you should use convert. tostring. If you want it to be null and throw an exception, you can select tostring.

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.