Data type (2)-type conversion

Source: Internet
Author: User

Type conversions are divided into three types, one between value types, one between reference types, and the last is between value types and reference types.

Conversion between value types is simple, usually a conversion of numbers. The difference between some types of C # that can represent numbers is that they differ only in their range of values, such as Short,int,long. At this point, if you want to convert a data type with a smaller range of values to a type with a larger range of values, you will generally succeed (I cannot think of the reason for failure), and you can complete the implicit conversion without having to write out the type name. For example, convert short to int. But if you turn int to short, the implicit conversion must fail, and the compiler notifies us that the transformation has to use an explicit conversion. At this point we need to explicitly indicate the conversion type name in parentheses (even if you know the conversion will succeed):

            int 0 ;              Short bb = (short) AA;

Explicit conversions are mandatory, so if the conversion does not succeed (for example, converting 65537 to short), the overflow value is saved. For example, to convert 65537 to short, you will get a value of 1. By default, overflow does not throw an exception. If you want to catch a possible overflow and handle it, you can use the checked keyword to enclose the conversion statement you want to check, or {}. At this point, an exception is thrown if the conversion appears to overflow. You can use Try-catch to handle exceptions. Visual Studio provides a check for arithmetic overflow/underflow in the advanced of build in project properties, and checking it means automatically adding check for all conversion operations. We don't need to add one ourselves.

Of course, if you enable check for arithmetic overflow/underflow, but you don't want to throw an exception for a piece of code, you can use the unchecked keyword to wrap the code. Because it is the default behavior of the compiler to not throw exceptions, the unchecked keyword is useful only if the check for arithmetic overflow/underflow is enabled globally.

Conversions between reference types are also common. For inheritance between parent classes and subclasses, we can compare the value types of short and int. But the situation ratio type is slightly more difficult to understand. Suppose, for example, that we have a class rectangle (the constructor eats three variables), which I did not understand at all in the following line of code:

Object New Rectangle (""12);

So what's the type of C? Suppose that the class rectangle has a method area, return the rectangle, then we can try to call C.area, at this time the compiler error, we see that there is actually C does not exist this method, so C should be the object type. But I call C. GetType (), the return is rectangle. So what happened after this line of code was executed? This is actually the case:

First of all, C is the object type and this is definitely no problem (otherwise C will have all rectangle methods, not actually). Before executing to new, the system allocates a site on the stack, a reference to C. (There is no pointer at this point) when you execute new, the system allocates another piece of land on the heap (its size equals the sum of the size of all value type attributes + Reference type attributes), and then points the pointer on the stack to the site on the heap rectangle. The type returned by GetType () is not the type of reference on the stack, but the type of site on the heap that the stack points to. At this point, because the reference itself and the end point pointed to by the pointer are different types, but the former is large, there is no problem with implicit conversions.

So the question comes, what if I turn around?

New Object ();

Guess you can guess, it's obviously not going to work. If you intend to explicitly convert, you can still do this by specifying a conversion type:

            Object New Object ();             = (rectangle) x;

This time, however, unlike the value type, if it fails, the compiler does not know how to handle the overflow (the concept of overflow actually refers to a number), so it will burst with runtime errors! Try-catch is certainly a solution, but C # also provides fast detection with the AS keyword:

 as Rectangle;

At this point, if the value of D is null, it means that the conversion failed. You can handle it later, without throwing any exceptions.

The reciprocal conversion of value types and reference types is known as boxing and unboxing. As previously mentioned, this conversion is certainly the most complex, because the number of components of both types is different. So, when the value type is converted to a reference type (boxing), we want to allocate extra space on the heap, plus a pointer. Specifically, that is:

    1. Calculate the size of the memory that should be allocated on the heap, note that this size includes additional pointers
    2. allocating memory on the heap
    3. Returns the address of a value type (now the value type on the stack becomes a reference to an object on the heap)

Unpacking is simple:

    1. Gets the address of all properties on the heap for the target object
    2. Copy the values contained in these properties (obtained by address) to the value type instances on the stack
int i=0; System.Object obj=i; Console.WriteLine (i+","+ (int) obj);

In this example, a total of 2 boxes and one unboxing were taken. Unpacking is the third line when obj is converted to type int and 2 boxing occurs in the WriteLine method. When trying to build a string, the system implicitly calls the Concat method, and all of its variables are object. So I and (int32) obj all need to be boxed.

Note "," is already a string, and the string is a reference type. The reference type is always boxed and therefore does not need to be boxed again.

Boxing and unboxing are all processes that require a lot of computation. when you are boxing a value type, you must create a completely new object. This operation takes 20 times times longer than a simple reference assignment operation. when unboxing is canceled, the casting process takes up to four times times the value of the assignment operation. (http://msdn.microsoft.com/zh-cn/library/ ms173196.aspx) in the array of objects you can put anything in the collection, all the members are object, traverse him and modify the possible number of boxing unboxing is very large, performance will be severely affected. C # introduced generics in version 2.0 to replace this weakly typed collection object (the DataTable is another example).

Data type (2)-type conversion

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.