(4/∞) Value types and reference types in C#

Before understanding the data types in C#, introduce two concepts:

Stack thread stack: The stack is managed by the operating system and stores the addresses used to store value types and reference types on the managed heap. The stack is based on threads, and a thread contains a stack.

GCHeap heap:  The memory space divided on the process address after the process is initialized, used to store .NET runtime objects, managed and released by GC.

The following is the value type reference type table

 The constructor of the following class

    public Text()
	{
		int i = 1;
	}

 Among them, the integer variable i is stored on the stack .

Another example is a class Test. From the above, we can know that the class is a reference type, which is stored in the Heap heap address of the memory, and all the fields and attributes in the class are stored in the heap instead of the stack.

        class Test {
        public int a;
        public int A { get; set; }
        public string str;
    }

 Once this class is instantiated, all members are stored in heap memory.

Knowing so much, what is the specific difference between value types and reference types?

1 The assignment method is different : when assigning a value type to a value type, the value of the variable is directly assigned and passed, and the reference type is passed the address on the heap.

2 Inheritance : Value types cannot derive new types, and all value types inherit System.ValueType by default, but structures can inherit interfaces. The following is a structure that inherits the interface and implements a method, an attribute, and an indexer in the interface.

        interface IFly {
        public void Fly();

        public string Name { get; set; }

        int this[int index] {
            get;
            set;
        }
    }
    struct Test : IFly
    {
        public int this[int index] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

        public string Name { get; set; }

        public void Fly()
        {
            
        }
    }

3. Default value : Each value type has a default constructor, the default value is 0, and the reference type defaults to null.

4. Needless to say, the storage location?

Guess you like

Origin blog.csdn.net/qq_52690206/article/details/127054429