C # Basic Types

Source: Internet
Author: User

After spending nearly half a year, I finally read the book "CLR Via C #" (please do not BS read Speed T_T). This is indeed a good book, what we recommend is worth reading.

Although many things have not been fulfilled, I often want to summarize and share them after I have mastered a certain knowledge point (I don't know if everyone is in this mentality ), but now I think this should be done in the process of a person's growth, so with this unwritten summary, a lot of knowledge points in this article come from the book CLR Via C, thank you to the author and the translator! If there is any error in this article, you are welcome to point it out!

Glossary:

CLR: Common Language Runtime)

FCL: Framework Class Library)

IL: Intermediate Language)

Type Basics

 CLR requires that all types are ultimately derived from System. Object. This is in line with the object-oriented language and design, everything is an object!

, We can see that the explicit class ExplicitlyDerivedFromObject derived from System. Object is consistent with the class ImplicitlyDerivedFromObject without explicitly specifying its parent class. If we do not specify a class parent class, the compiler automatically adds the System. Object parent class to our class.

Primitive type

The data types directly supported by the compiler are called Primitive types. Each Primitive type corresponds to a type in FCL. As shown in the following table, each primitive type corresponds to the corresponding FCL type:

We can also simply understand that the compiler will automatically add the following using commands to each of our source code files (using serves as an alias for the type ):

using int = System.Int32;using string = System.String;……

After understanding this, we should be able to know whether to write int or Int32 in our code, and whether to use string or String is essentially the same! The results of the IL code generated by the two different writing methods below are also expected.

We should also know,In C #, the int always represents a 32-bit integer, and the long always represents a 64-bit integer.. This may be different from other programming languages (for example, C/C ++ may decide based on the platform, for example, int may be 16-bit on a 16-bit machine, however, on 32-bit machines, it may be 32-bit. I have long forgotten that C/C ++ is vague. If there is an error, please point it out !).

Reference Type and Value Type

CLR supports two types:Reference TypeAndValue TypeThey differ in memory allocation methods: the reference type is allocated from the managed stack, and the value type is allocated on the thread stack. The CLR garbage collection is for the managed heap, so the value type is not controlled by the garbage collector.

In FCL, all types called "structures" (struct) are value types, and all types called "Classes" are reference types. All Struct values are directly derived from the abstract class System. ValueType, while System. ValueType is directly derived from System. Object. All enumeration types are derived directly from System. Enum, and the latter is derived from System. ValueType. Therefore, enumeration is also a value type. Because of the unique inheritance rules of CLRThe base type cannot be specified when defining the value type, but the interface can be implemented.. At the same time, we can see from the generated IL that,Value Type is implicitly sealed(Sealed), that is, it cannot be derived from the value type.

Although the reference type and value type are actually only differences in memory allocation, this difference will lead to a significant difference in the behavior of the two types, such as the following example:

Struct ValType {public int x;} class RefType {public int x;} class Program {static void Main (string [] args) {ValType v1 = new ValType (); // allocate memory on the stack RefType r1 = new RefType (); // allocate memory on the stack v1.x = 2; r1.x = 2; // execute here, see Figure 1 Console for the memory structure. writeLine (v1.x); // 2 Console. writeLine (r1.x); // 2 ValType v2 = v1; // allocate memory (v2) on the stack, and copy the content of the v1 stack to v2 RefType r2 = r1; // copy the heap address of r1 to r2 v2.x = 5; // only change the content of v2 stack r2.x = 5; // because both r2 and r1 reference the object on the same stack, changing r2 will also change r1 // run here. The memory structure is shown in Figure 2 Console. writeLine (v1.x); // 2 Console. writeLine (r1.x); // 5 note that the Console is changed to the value after R2. writeLine (v2.x); // 5 Console. writeLine (r2.x); // 5 Console. readKey ();}}

First, we define a value type and a reference type. Each field has only one field. When memory is allocated using the new operator, the memory of Value Type v1 is allocated on the thread stack, and the memory of reference type r1 is allocated on the managed stack. When the program runs until the first WriteLine output, the result is consistent. But when two new objects are declared and assigned values are executed, what happens here is obviously different: although the assignment operation is to copy the variable content on the thread stack, however, because the stack content of the Value Type Variable v1 is the ValType instance itself, and the stack content of the reference type r1 is the address of the RefType object instance on the stack. Therefore, after the value is assigned, v1 and v2 each save a ValType instance, while r1 and r2 Save the address of the same heap memory. Therefore, changing the r2 object causes the r1 object to change along with the change. Below is the memory:

 

Figure 1

 

Figure 2

Although a value-type instance does not require garbage collection, it is not suitable to define a value type as a value type because the content itself is passed when the value type is passed. UnlessAll of the following conditions are met:Otherwise, a type should not be declared as a value type.

  • The member whose field is not changed, that is, the type is unchangeable. (We recommend that all fields be readonly)
  • Types do not need to be inherited from any other types. (The base class cannot be selected for the value type)
  • No other types are derived. (All value types are implicitly sealed)
  • The instance is small (about <= 16 Byte) or large, but not passed as a real parameter of the method, and is not returned from the method.
Binning and unboxing value types

The process of converting a value type into a reference type is called packing. The whole process looks like this:

  1. Allocate memory in the managed heap, and allocate memory = memory required for each field of value type + two additional members for all objects on the stack (type object pointer and synchronized block index) the amount of memory required.
  2. Copy fields of the value type to the allocated memory.
  3. The address of the returned object.

The binning is only a process of getting a pointer that points to the original value type (data field) contained in an object ). Although unpacking costs less than packing, it is usually followed by a value assignment operation (memory replication) after unpacking ). Obviously packing and unpacking/copying will adversely affect the speed and memory consumption of the application, so we should understand this andAvoid packing and unpacking as much as possibleOperation. The most intuitive way is to look at the generated IL code (the commands corresponding to IL are box and unbox respectively). For example:

In the example, the Add method parameter of ArrayList is of the Object type, that is, a reference type (memory allocated on the stack). When we pass the int type, the int instance is boxed here, to return the address of a stack. When the array [0] is forcibly converted to an int, because the int object of the value type is allocated on the thread stack, the box is split and the value assignment (memory replication) operation is immediately followed. At the same time, for comparison, I added a reference type, we can see that the reference type will not be boxed or unpacked.

How to Avoid (or reduce) packing and unpacking:

  • Use a generic set whenever possible.
  • Try to move the packing and unpacking operations out of the loop body.
  • Define a method. If you can receive the reference type or value type, try not to define the parameter as an object. You can consider defining multiple versions or defining generic methods by reloading them.
Summary

This article can only be a summary of reading a book by yourself. The purpose of sharing this article is to hope that if you have incorrect understanding of some knowledge, you will be able to correct it in time. If you feel that this blog post has a little value, then I achieved my second goal.

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.