Home  >  Article  >  Backend Development  >  Detailed introduction to value types and reference types in C#

Detailed introduction to value types and reference types in C#

黄舟
黄舟Original
2017-10-01 07:24:471232browse

This article mainly introduces the relevant information of value types and reference types in C# in detail. It has certain reference value. Interested friends can refer to it

In C#, value types Reference types and reference types are two very important concepts. The behavior of type instances must be determined when designing the type. If you do not understand the difference between reference types and value types when writing code, unnecessary exceptions will be brought to the code. Many people encounter many problems in the programming process because they do not understand these two concepts. Here, the blogger briefly talks about the understanding of value types and reference types.

First of all, conceptually, value types store their values ​​directly, while reference types store references to their values. Thus the two types are stored in different places in memory.

Secondly, from the perspective of memory space, value types operate on the stack, while reference types allocate storage units in the heap.

The stack allocates memory space during compilation, and the stack is clearly defined in the code. The heap is a memory space dynamically allocated during program running. The size of the memory can be dynamically allocated according to the running status of the program. . Therefore, value types always occupy a predefined number of bytes in memory. A reference type variable allocates a memory space on the stack. This memory space contains a reference to another memory location. This location is an address in the managed heap, where the actual value of the variable is stored.

That is to say, the value type is equivalent to cash. If you want to use it, just use it directly, while the index type is equivalent to a passbook. If you want to use it, you have to go to the bank to get it first.

But value types allocate memory on the stack, while reference types allocate memory on the managed heap. This is just a general statement. This is described in detail below.

(1) For an instance of a value type, if it is used as a local variable in a method, it is created on the thread stack; if the instance is used as a member of the type, it is used as part of the type member, together with other type fields Stored on the managed heap.

Each value type has an implicit default constructor to initialize the default value of that type. For example:


int i = new int();

is equivalent to:


Int32 i = new Int32();

is equivalent to:


int i = 0;

Equivalent to:


Int32 i = 0;

When using the new operator, the default constructor of a specific type will be called and the variable will be assigned a default value. In the above example, the default constructor assigns the value 0 to i.

Note: All value types in C# are implicitly derived from System.ValueType, and System.ValueType is directly derived from System.Object. That is, System.ValueType itself is a class type, not a value type. The key is that ValueType overrides the Equals method so that value types are compared according to the value of the instance instead of the reference address.

(2) Instances of reference types are created on the managed heap.

The following is a piece of code to explain in detail the difference between value types and reference types


namespace Test 
  { 
      class Program 
      { 
        static void Main(string[] args) 
        { 
       //调用ReferenceAndValue类中的Demonstration方法 
          ReferenceAndValue.Demonstration(); 
          Console.ReadLine(); 
        } 
      } 
      public class stamp       //定义一个类 
      { 
        public string Name { get; set; }    //定义引用类型 
        public int Age { get; set; }    //定义值类型 
      } 
      public static class ReferenceAndValue   //定义一个静态类 
      { 
        public static void Demonstration()   //定义一个静态方法 
        { 
          stamp Stamp_1 = new stamp { Name = "Premiere", Age = 25 }; //实例化 
          stamp Stamp_2 = new stamp { Name = "Again", Age = 47 }; //实例化 
          int age = Stamp_1.Age;     //获取值类型Age的值 
          Stamp_1.Age = 22;     //修改值类型的值 
          stamp guru = Stamp_2;     //获取Stamp_2中的值 
          Stamp_2.Name = "Again Amend";   //修改引用的Name值 
          Console.WriteLine("Stamp_1's age:{0}", Stamp_1.Age); //显示Stamp_1中的Age值 
          Console.WriteLine("age's value:{0}", age); //显示age值 
          Console.WriteLine("Stamp_2's name:{0}", Stamp_2.Name); //显示Stamp_2中的Name值 
          Console.WriteLine("guru's name:{0}", guru.Name); //显示guru中的Name值 
        } 
    } 
  }

After running the above program, we can see that when the change When the value of Stamp_1.Age is changed, age does not change, but after changing the value of anders.Name, guru.Name changes. This is the difference between value types and reference types. When declaring the age value type variable, assign the value of Stamp_1.Age to it. At this time, the compiler allocates a space on the stack, and then fills in the value of Stamp_1.Age. There is no connection between the two, just like in It is the same as copying files on the computer, except that the value of Stamp_1.Age is copied to age. The reference type is different. Stamp_2 is assigned to guru when declaring it. As mentioned before, the reference type only contains a reference to the address of the data area on the heap. In fact, the reference of Stamp_2 is also assigned to guru, so they point to the same block. memory area. Since it points to the same area, no matter who modifies it, the value of the other one will change accordingly. Just like a credit card and a family card, if you withdraw money with a family card, the credit card account associated with it will also change.

The above is the detailed content of Detailed introduction to value types and reference types in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn