C # Type Conversions

Source: Internet
Author: User

1. Implicit conversions:

Small data type ranges are converted to large data types such as

int i=100;

Long j=i;

Subclass conversion to base class

2. Display conversion

First Kind

Long j=100;

int i= (int) j; Data loss may occur

The second Kind

Convert by some type of method, such as Int. Parse ("11");

The above two methods, if the converted data can not be converted to the corresponding target class, will be reported when compiling the exception.

So you can use the following two ways to judge

int test;

A.bool Result=int. TryParse ("ASD", out test);

The above code does not report that an exception cannot be converted when an int is assigned the default value of Test=0.

B. You can use the AS keyword for reference types and nullable types

Class1 c1= (C1) C2;

The above code will report an exception

Class1 C1=C2 as Class1 should be used;

If the conversion is not normal, the value of C1 is null.

3. Crating and Unpacking

Boxing is the conversion of a value type to an application type

The reverse is the unboxing, that is, the stack of data and the data of the heap conversion. Easy to consume the resources of the computer, so avoid boxing and unpacking as much as possible.

4.Nullrable

Nullable type. int?a=3; The numeric type that represents int can also be empty. There is also a way to system.nullable<int> test2 = 100;

int test=a?? 500; The usage indicates that if a is NULL then you are assigned the default value of 500.

---fight like a man!

C # Type Conversions

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.