"Go" the difference between a C # reference type and a value type large inventory

Source: Internet
Author: User
Tags access properties

Parsing: The CLR supports two types: value types and reference types. In the words of Jeffrey Richter (the CLR via C # author), "Programmers who don't understand the difference between reference types and value types will introduce code into weird traps and many performance problems." This requires that we understand and use value types and reference types correctly.

Value types include the basic type of C # (declared with the keyword int, char, float, and so on), structure (type declared with the struct keyword), enumeration (type declared with the enum keyword) Whereas reference types include classes (types declared with the class keyword) and delegates (special classes declared with the delegate keyword).
Each of the types in C # is either a value type or a reference type. So each object is either an instance of a value type or an instance of a reference type. Instances of value types are typically allocated on the thread stack (static allocations), but in some cases can be stored in the heap. Objects of reference types are always allocated (dynamically allocated) in the process heap.
(1) in C #, a variable is a value or a reference only depending on its base data type. the basic data types of C # are platform-Independent. C # Predefined types are not built into the language, but are built into the. NET Framework: NET uses the common type System (CTS) to define predefined data types that can be used in intermediate language (IL). All data types in C # are objects. They can have methods, properties, and so on. For example, when declaring an int variable in C #, the declaration is actually an instance of System.Int32 in the CTS (common type System):

1 int  213string4

(2) System.Object and System.ValueType. both the reference type and the value type inherit from the System.Object class. The difference is that almost all reference types inherit directly from System.Object, whereas value types inherit their subclasses, that is, they inherit System.ValueType directly. As a base class for all types, System.Object provides a set of methods that can be found in all types. It contains methods such as ToString and clone. System.ValueType inherits System.Object. It does not add any members, but overrides some of the inherited methods to make them more suitable for value types.
(3) value type. all value types in C # are implicitly derived from System.ValueType:
struct: struct (directly derived from System.ValueType).
Numeric type: integer, SByte (alias of System.SByte), Short (system.int16), int (System.Int32), Long (System.Int64), Byte (System.Byte), ushort (system.uint16),
, UINT (SYSTEM.UINT32), ULONG (System.UInt64), char (System.Char).
Float type: float (system.single), double (system.double).
High-precision decimal type for financial calculations: decimal (System.Decimal).
BOOL Type: bool (alias of System.Boolean).
User-defined struct (derived from System.ValueType).
Enum: Enum (derived from System.Enum).
Nullable type. Each value type has an implicit default constructor to initialize the default value for that type. For example:

int i = 0;
Equivalent to:
int i = new int ();

When you use the new operator, a specific type of default constructor is called and the variable is given a default value. In the example above, the default constructor assigns the value 0 to I.
All value types are sealed (seal), so new value types cannot be derived.
It is worth noting that 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 to compare the value type against the value of the instance, rather than the reference address. You can use the Type.isvaluetype property to determine whether a type is a value type:

1 New  2if34 Console.WriteLine ("{0} is Value type. "  5

(4) reference type. C # has some of the following reference types:
Array (derived from System.Array)
The user needs to define the following types.
Classes: Class (derived from System.Object);
Interface: Interface (interface is not a "thing", so there is no question of where to derive it.) The interface simply represents a contract convention [contract]).
Delegate: Delegate (derived from System.Delegate).
Object (alias of System.Object);
String: String (alias of System.String).
Can be seen:
A reference type is the same as a value type, a struct can also implement an interface, a reference type can derive a new type, a value type cannot, a reference type can contain a null value, a value type cannot, and an assignment of a reference type variable copies only the reference of the object, not the object itself. When you assign a value type variable to another value-type variable, the contained value is copied.
(5) memory allocation. instances of value types are often stored on the stack. But there are also special cases. If an instance of a class has a field of value type, the field is actually stored in the same place as the class instance, which is the heap. However, objects of reference types are always stored in the heap. If a struct's field is a reference type, only the reference itself is stored with the struct instance (on the stack or heap, depending on the case). As shown in the following example:

1  Public structvaluetypestruct2 { 3 Private ObjectReferencetypeobject;4  Public voidMethod ()5 { 6Referencetypeobject =New Object(); 7 ObjectReferencetypelocalvariable =New Object(); 8 } 9 } TenValuetypestruct valuetypestructinstance =Newvaluetypestruct (); OneValuetypestructinstance.method ();
Where are referencetypeobject and referencetypelocalvariable stored?

See Valuetypestructinstance, this is a struct instance, it feels as if the whole block is on the stack. But the field referencetypeobject is a reference type, and the local variable referencetypelocalvarible is also a reference type.

1  Public classReferencetypeclass2 { 3 Private int_valuetypefield;4  PublicReferencetypeclass ()5 { 6_valuetypefield =0; 7 } 8  Public voidMethod ()9 { Ten intValuetypelocalvariable =0;  One }  A }  -Referencetypeclass referencetypeclassinstance =NewReferencetypeclass (); - //where is _valuetypefield stored? the Referencetypeclassinstance.method (); - //where is valuetypelocalvariable stored?

Referencetypeclassinstance also has the same problem, referencetypeclassinstance itself is a reference type, and it seems that the entire block should be deployed on the managed heap. But field _valuetypefield are value types, local variable valuetypelocalvariable are also value types, are they on the stack or on the managed heap?
The correct analysis of the above situation is that the reference type stores a reference in the stack whose actual storage location is in the managed heap. For convenience, the abbreviation reference type is deployed on the managed heap. A value type is always allocated where it is declared, as a field, followed by the variable (instance) to which it belongs, and stored on the stack as a local variable.
(6) Identify the use of value types and reference types. In C #, we use Struct/class to declare a type as a value type/reference type. Consider the following example:
sometype[] Onetypes = new sometype[100];
If SomeType is a value type, only one allocation is required and the size is 100 times times that of SomeType. If SomeType is a reference type, it requires 100 allocations at the beginning, the element value of the array after the allocation is null, and then the 100 elements are initialized, resulting in a total of 101 allocations. This will consume more time, resulting in more memory fragmentation. Therefore, if the type of responsibility is primarily to store data, the value type is more appropriate.
In general, value types (which do not support polymorphism) are suitable for storing data for C # application operations, whereas reference types (which support polymorphism) should be used to define the behavior of the application. Typically, we create more reference types than value types. If the following conditions are true, then we should create a value type: The primary responsibility for this type is for data storage.
The common interface for this type is entirely defined by some data member access properties.
The type can never have subclasses.
The type does not have polymorphic behavior.
Answer: In C #, a variable is a value or a reference only depending on its data type. The value types of C # include: struct (numeric type, bool type, user-defined struct), enumeration, nullable type.
The reference types of C # include: arrays, user-defined classes, interfaces, delegates, object, strings. The elements of an array, whether they are reference types or value types, are stored on the managed heap.
A reference type stores a reference in the stack whose actual storage location is in the managed heap. The abbreviation reference type is deployed on the managed push. A value type is always assigned where it is declared: as a field, it is stored as a variable (instance) to which it belongs, and is stored on the stack as a local variable. Value types are more efficient in memory management and do not support polymorphism for use as a carrier for storing data; reference types support polymorphism and are suitable for defining the behavior of an application

"Go" the difference between a C # reference type and a value type large inventory

Related Article

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.