value type reference type

The biggest difference between value types and reference types is the difference in memory allocation :

Stack stack: Thread stack, managed by the operating system, stores value types , reference type variables ( referencing the address of the object on the managed heap ). A thread contains a thread stack, which is cleaned up after the object scope ends, which is highly efficient.

GC Heap managed heap: stores reference types , allocated objects are managed and released by GC, based on process.

Are value types always stored on the stack? Are all reference types stored on the managed heap?

1. A separate value type variable is stored on the stack;

2. As a field of the class, the value type will be stored on the managed heap along with the reference type as part of the reference type;

3. The reference type is always stored on the managed heap, but the reference type variable (the address of the reference type object on the managed heap) is stored on the stack.

The difference between a structure and a class :

Structs are value types and classes are reference types.

1. The structure does not support custom no-argument constructors. Custom constructors can only have parameters. To retain the default no-argument constructor, destructors are not supported. C# cannot have protected modifiers, and inheritance is not supported. Members Variables cannot define initial values;

2. Class supports abstraction, but struct does not support abstraction;

When a type is only a collection of primitive data and does not require complex operations, it should be designed as a struct, otherwise it should be designed as a class .

The difference between out and ref: ref needs to be initialized.

It’s great to see an article written: https://www.cnblogs.com/anding/p/5229756.html

 

Guess you like

Origin blog.csdn.net/l17768346260/article/details/103745903