C # Value types and reference types

Source: Internet
Author: User

Data has value types and reference types, and we usually call constants of reference types as instances

One, the constant storage location is different:
The value type constant is in the stack, and the instance is in the managed heap.

The corresponding relationship between variables and constants is different:
The independence of a value type variable: the constant itself is stored in the variable's own storage space, and a variable corresponds to a constant.
A many-to-one relationship between a reference type variable and an instance: The variable only holds the address where the constant is, and the same instance can be referenced by multiple variables.

Three, the internal operation is different when initializing variables:

1. Initialize value type variables
When a value type variable is assigned a value, the constant is copied and placed in the variable.

2. Initializing reference variables
When assigning a value to a reference type variable, the address of the instance is stored in the variable.
3. Packing
If a value type constant is used to assign a value to a reference type variable, the CLR attempts to wrap an instance based on that constant, and then place the instance address in a variable.

int a=5; Object o=a; // boxed, according to 5 is wrapped a reference type constant, with O to save the object address. 

Summary: For the sake of efficiency, the integral type, float type These common types are set to the value type.
However, some CLR functions only accept reference type parameters, so there are boxing and unboxing to wrap the operand type constants into the corresponding reference types to facilitate manipulation.

C # 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.