. Net Value Type and Reference Type 101

Source: Internet
Author: User
1.1.1 Summary

What is the value type? What is a reference type? This issue has been discussed and studied for a long time, and I believe many people are familiar with the differences and usage of value types and reference types. Here I will give my own summary, and also provide you with an opportunity to review value types and reference types.

Familiar with C/C ++ProgramYou know that you can create pointers for any type of objects to reference them. This is not Java, and any type is automatically declared as the reference type. Then, the type in C # provides the value type and reference type.

1.1.2 text

Figure 1 outline of value type and reference type

If the value type is used to store the object value, the reference type is used to store the reference value of the object. Is that true? I have seen many people say: "The value type is used to store the value, and it cannot or shouldn't. Storage methods and actions "In my opinion, the value type not only stores values, but also stores methods and actions. For example, datetime and decimal are undoubtedly value types. NET provides many methods and actions for this type, so that datetime and decimal functions are powerful.

Values of the value type are stored in the stack, and objects of the reference type are stored in the heap. Is that true? I think this depends on the language. As we mentioned earlier, the C/C ++ type is defined as the value type, the types in Java are defined as reference types (precondition 1), and we should not think that the storage area is static, depending on the specific language, maybe monkey Ma Yue C # will put some reference types in the stack.

There is also a problem that the reference type object is stored in the heap, but the value type value should be determined based on the definition of the value type, for example, we define a value type as a local variable in a method and a field in a class respectively. The storage area is different, and the former is stored in the stack, the latter is stored in the heap (prerequisite 2 ). In addition, I believe that when I go to school, the teacher will talk about the value type and reference type storage area-stack. In the future, I will add a pair of preconditions.


    • Based on the specific language
    • Specific Definition Based on Value Type

Figure 2 Storage of value type and reference type

The above briefly describes how the value type and reference type are stored in memory. The value type data is stored in the stack, and the reference value of the reference type is stored in the stack, objects and data values are stored in the heap. in the predefined types provided in. net, all types except object and string are value types. Let's talk about the value type and reference type through specific examples.

OK first, we define a custom class, and then add two fields _ index and _ description. For the sake of simplicity, we do not use attributes. The specific example is as follows:

/// <Summary> ///A custom clase./// </Summary>Public classCustomtype{/// <Summary> ///_ Index is value type.///_ Description is reference./// </Summary>Private int_ Index;Private string_ Description ;}

Suppose we instantiate an object of this type, and then let's analyze how the object is allocated in the memory, so it's time to draw.

    • Objects and data of the reference type are always stored in the heap.
    • Reference Values of the value type and reference type can be stored on the stack or stack depending on the language environment


Figure 3 storage of reference type

We can find that the object of the reference type is stored in the heap, which is undoubtedly, and the Value Type _ index defined in customtype is also stored in the heap, this fully demonstrates that the storage area of the value type should be determined according to the specific definition.

Next we will introduce a value type -- struct. We define a struct named customtype, and then add two fields, which are the same as those in the previous class. Now it's time for painting.

Figure 4 value-type storage

Now we instantiate a customtype object. Because we know that customtype is a value type, it will be stored in the stack, in addition, both the _ index value and the reference value of _ description are stored in the stack, and the specific value or object of _ description is stored in the heap.

Through the example of storing the reference type and value type objects in the memory, we know that we cannot say in general: "The value type is stored in the stack, and the reference type is stored in the heap ", the prefix conditions (Language type and definition type) must be added ).

Let's use a simpleCodeThe difference between the value type and the reference type is shown. Here we use struct and class as an example.

 Public class  Mytype { /// <Summary> /// This class has two fields.  /// </Summary>  Private  Customtype Type1; Private  Customtype Type2; /// <Summary> ///  Initializes a new instance of  <See CREF = "mytype"/>  Class.  /// </Summary>  Public Mytype (){ This . Type1 = New Customtype (); This . Type2 = New  Customtype ();}}
/// Instantiates a object of mytype.MytypeMytype =NewMytype();

Now let's analyze the size and number of times of memory allocation when the customtype type is struct and class (assuming it is under 32-bit CLR ).

First, when mtmtype is a struct, only one memory allocation is required. The size is twice the size of customtype. Because customtype is 8 bytes, mytype allocates 16 bytes of space. If customtype is a class, we need to allocate three times of memory, one is allocated in the heap of the mytype object, and the other two are allocated in the heap of the customtype object.

Here is a simple example:

Mytype[] Var =NewMytype[888];

If mytype is a value type, you only need to allocate it once. The size is 888 times the size of the mytype object. However, if mytype is a reference type, an allocation is required at the beginning, and the element values of the allocated array are null. If you initialize each element in the array, we will need to execute a total of 889 allocation times-889 allocation takes more time than one allocation. Allocating many reference type objects will cause many fragments in the heap space, thus reducing the system speed.

Many people say: "struct is a lightweight class." They think it is better than a Class Based on struct efficiency, but I think this is not comprehensive enough, through the preceding two examples, we can see that the struct is indeed more efficient than the class, because the value type does not require garbage collection (except for the boxed value type), and there is no Type Recognition overhead. However, if we want to copy a large amount of data, the value type needs to be copied to initialize the value of each variable, and the reference type only needs to copy the reference value.

MytypeT1 =NewMytype();MytypeT2 = T1;

Figure 5 value type reference type assignment

Through the above example, we found that when mytpye is a value type, we need to copy n times, and the reference type only needs to be copied once. If the data volume to be copied is multiple values, the type efficiency is lower than that of the reference type. Because you only need to copy the reference value for the reference type.

Differences between value types and reference types:

    • Is the primary role of this type used for data storage?
    • Is this type of public interface completely defined by some data member access attributes?
    • Are you sure this type can never be a subclass?
    • Are you sure this type will never have polymorphism?

Packing and unpacking

Boxing is a mechanism provided by. Net to generate an object based on the value type. unboxing is to extract the value from the object and put it in the corresponding value type. Here is a simple example.

IntI = 5;ObjectO = I;// BoxingIntJ = (Int) O;// Unboxing

We define a Value Type I and a reference type O. Boxing occurs when the value type I is assigned to O, and unboxing occurs when the object o is assigned to J. However, we should note that if boxing is long, and unboxing to int will throw an invalidcastexception. We can handle the conversion exception in the following ways, but this leads to unnecessary redundancy and missing precision for the code, so we should be consistent with the boxing variable type during unboxing.

LongI = 5;
ObjectO = I;// Boxing
IntJ = (Int)(Long) O;// Unboxing

Through the previous example, we found that there is no identifier for the conversion between Boxing and unboxing. We can only judge the occurrence of boxing and unboxing Based on the conversion between the value type and the reference type. To help you understand this, consider the number of boxing and unboxing operations in the following code:

ArraylistList =NewArraylist(); List. Add (22); list. Add (23); list. Add ((Int) List [0] + (Int) List [1]);Foreach(IntIInList ){Console. Writeline ("Number is: {0}. \ n", I );}

First, we add two value types to the list array. Because the add () method accepts the object type parameter, two boxing operations are required.

Next, we take the two objects in the list for processing, and convert them to the value type for addition operation. This requires two unboxing operations. Finally, we need to store the results in the list for the boxing operation.

When traversing the list, we need to save the value in the list to I for the unboxing operation. Then we call console. writeline (string format, object Arg) to perform the boxing operation on I.

Therefore, four boxing and three unboxing operations were performed. Fortunately, there are not many boxing and unboxing operations, which has no significant impact on our program efficiency, however, frequent boxing and unboxing operations will have immeasurable impact on our programs. net proposes a reason to use generics.

In the above example, I think the cause is relatively hidden in the writeline () method. because too many parameters are used at ordinary times, I do not pay attention to the parameter type passed by this method.

Next, we will use some more confidential examples to explain when the boxing operation will take place.

IntI = 23; I. tostring ();//I. gethashcode ();// BI. GetType ();// CI. gettypecode ();// D

Let's take a look at the boxing operation of the method. The exciting time is coming to let us announce the answer-C.

The reason is simple: the object. GetType () method cannot be rewritten. Therefore, the value type Integer does not implement its own GetType method, and the object's GetType () method can only be called through the boxing operation.

Figure 6 msil code


1.1.3 Summary

This article mainly introduces what is the value type and reference type, and their distribution in memory. We can see the difference between the value type and the reference type:

    • The reference type stores the reference value of the object, rather than the object itself.
    • The value type is the specific data.
    • In many cases, the value type is more efficient than the reference type, but there are exceptions.
    • Objects of the reference type are stored in the heap, while value-type data can be stored in the stack or heap.
    • The Value Type value can be converted to the reference type through boxing, and to the value type through unboxing

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.