. Net framemwork storage for value types and reference types

Source: Internet
Author: User

C # divides data types into two kinds: value types and reference types. Value types are stored on the stack, and reference types are stored on the managed heap.

Storage of value types and reference type variables
First, variables are the basic unit for storing information, and for internal computers, variables are equivalent to a piece of memory space.
There are two kinds of variable data types in C #:
[1] Value type: Simple Type, struct type, enum type
[2] Reference type: Class, delegate, array, interface.

1. Value type and reference type memory allocation
Value types are manipulated in the stack, whereas reference types allocate storage units in the heap.

Stack in the compile time allocated memory space, in the code has a clear definition of the stack, and the heap is a program run dynamically allocated memory space, you can dynamically allocate the size of memory according to the program's running situation. Therefore, a value type always consumes a predefined number of bytes in memory (for example, an int occupies 4 bytes, or 32 bits). When declaring a value type variable, the memory space occupied by this variable type is automatically allocated in the stack, and the value contained in the variable is stored. NET automatically maintains a stack pointer that contains the address of the next available memory space in the stack. The stack is entered first, and the top variable in the stack is always out of scope before the following variable. When a variable leaves the scope, the stack pointer moves down the number of bytes consumed by the released variable, still pointing to the next available address.

Note that variables of value types must be initialized when they are used.
A variable of a reference type allocates a memory space in the stack that contains a reference to another memory location, which is an address in the managed heap, where the actual value of the variable is stored. NET also automatically maintains a heap pointer that contains the address of the next available memory space in the heap, but the heap is not first-in, and the objects in the heap do not leave the scope at a predefined point in the program, in order to release it when memory is not used in the heap. NET will perform garbage collection on a regular basis. The garbage collector recursively checks all object references in the application, and when it finds that the memory used by objects that are no longer valid is not accessible from the program, the memory can be reclaimed (except for fixed-keyword objects pinned in memory).
  But the value type allocates memory on the stack, and the reference type allocates memory on the managed heap, but it is a general statement. A more detailed and accurate description is:
[1] For instance of a value type, if it is a local variable in a method, it is created on the thread stack, and if the instance is a member of a type, it is stored on the managed heap as part of a type member, along with other type fields.
[2] An instance of a reference type is created on the managed heap, and if its bytes are less than 85000byte, it is created directly on the managed heap, otherwise it is created on the Loh (Large Objet heap).

For example, the code snippet:

     Public class Test     {         privateint i;    // as part of the test instance, is created on the GC heap         along with the instance of test  Public Test ()         {             int0;     // as a local real volume, an instance of J is created on the thread stack that executes the code.          }     }

2. Memory allocation of nested structures
A nested structure is a nested value type in a reference type, or a value type that is nested in a reference type.
Reference-type nested value types are the most common, and the example above is a typical example where value types are inline in reference types.
When a value type is nested in a reference type, the reference type is a variable that is a member of a value type, and a reference to the reference type is persisted on the stack, but the reference type is still allocated memory in the heap.

3, about the allocation of array memory
Consider the case when an array member is a value type and a reference type:
The member is a value type: For example int[] arr = new Int[5]. Arr saves a reference to the address of 4*5byte (int occupies 4 bytes) in the managed heap and assigns all elements to 0;
Reference type: myclass[] arr = new Myclass[5]. Create a reference to the managed heap in the stack of the ARR thread. All elements are set to NULL.

effect of value types and reference types on passing parameters
Because value types store their data directly in the stack, when a parameter of a value type is passed to a method, a new copy of the value is created and passed, and any modification to the parameter does not cause the variable passed to the method to be modified. A reference type, which simply contains a reference, does not contain the actual value, so any modifications that are made to the method's body parameters will affect the variable that is passed to the reference type of the method call.
This is demonstrated by the following procedure:

     classProgram {/// <summary>         ///The main entry point for the application. /// </summary>[STAThread]Static voidMain (string[] args) {             inti =0; int[] Intarr =New int[5];            Class1.setvalues (I,intarr); //The result of the output will be: i=0,intarr[0]=10Console.WriteLine ("I={0},intarr[0]={1}", i,intarr[0]);        Console.read (); }         Public Static voidSetvalues (intIint[] intarr) {i=Ten;  for(intj =0; J < Intarr.length; J + +) {Intarr[j]=i; }         }     }


three, packing and unpacking
Boxing: Converting a value type to an object type (object);

Unboxing: Explicitly converts an object type to a value type.

For boxing, it is copying a copy of the boxed value type, and for unpacking, you need to be aware of type compatibility, for example, you cannot convert an object type with a value of "a" to the type of int.
You can use the following procedure to illustrate:

        Static voidMain (string[] args) {             inti =Ten; //Packing             Objecto = i;//Object Type            if(O is int)             {                 //description has been boxedConsole.WriteLine ("I have already been boxed"); } I= -;//change the value of I//Unpacking             intj = (int) O; //The result of the output is 20,10,10Console.WriteLine ("i={0};o={1};j={2}", i,o,j);         Console.ReadLine (); }


Iv. about String
String is a reference type, but it is a little different from other reference types. Can be seen from the following two aspects:
(1) The string class inherits from the object class. Rather than System.ValueType.
(2) string is essentially a char[], and array is a reference type, which is also allocated memory in the managed heap.
However, when string is passed as a parameter, it has the characteristics of a value type, and when a variable of type string is passed inside the method, the value of the variable does not change after the method is left. The reason is that whenever you modify the value of a string, a new object is created. For example, the following procedure:

Class Class1
{
<summary>
The main entry point for the application.
</summary>
[STAThread]
static void Main (string[] args)
{
String a = "1111"; A is a reference that points to an instance of the string class
String B = A; Both B and a are the same object

At this point B and a are not the same object, because after assigning a value to B, a new object has been created and a reference to the new string object is assigned to B.
b = "2222";

So the value of a does not change, the output a=111.
Console.WriteLine ("A={0}", a);
Console.ReadLine ();
}
}
Note, however, that if you pass a value by reference, the value will change like the reference type's parameter, such as the following code:

Class Class1
{
<summary>
The main entry point for the application.
</summary>
[STAThread]
static void Main (string[] args)
{
String a = "1111";
Testbyvalue (a);

Output a=111.
Console.WriteLine ("A={0}", a);

Testbyreference (ref a);

When the value is passed by reference, it will change, output a= "".
Console.WriteLine ("A={0}", a);
Console.ReadLine ();
}

static void Testbyvalue (string s)
{
Setting the value
s = "";
}

static void Testbyreference (ref string s)
{
Setting the value
s = "";
}
}
V. about heaps and stacks in C #
There are two kinds of places where data is stored in C #: Heap and stack.
In the traditional C + + language, the stack is the data structure provided by the machine operating system, and the heap is provided by the C + + function. So the machine has a special register to point to the address of the stack, there is a special machine instruction to implement the data into the stack/stack action. The execution efficiency is high, but because of this, the stack generally only supports types that are directly supported by the system, such as integers, pointers, floating-point numbers, and so on. The heap is maintained by a library of C + + languages that is dynamically allocated memory. Stacks are allocated faster and have no memory fragmentation relative to the heap, but the supported data is limited.
In C #, value variables are allocated on the stack by the system. Used to assign fixed-length data (most of the value types have a fixed length). Each program has a separate stack and other programs cannot access it. When a function is called, the local variables that invoke the function are pushed into the program's stack. A heap is a type of variable-length data that is similar to C/s + +, except that in C/C + +, data is stored in the managed heap.
Because the value variable is allocated in the stack, assigning a value variable to another value variable duplicates two copies of the same data in the stack; instead, when you assign a reference variable to another reference variable, a reference to the same location is created in memory.
Allocation in the stack relative to the heap has the following characteristics:
(1) The distribution speed is fast;
(2) Automatically release the distribution after use;
(3) A variable of a value type can be assigned to another value type in the same way as the equal sign.

. Net framemwork storage for value types and reference types

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.