Common Type System—Reference and Value Types


Jump to: navigation, search
CSharp-Online.NET:Articles
.NET Articles

Common Type System

© 2006 Wiley Publishing Inc.

Reference and Value Types

As noted above, CTS types fall into one of two primary categories: reference types and value types. Reference types are often referred to as classes and value types as structures (or just structs), mostly a byproduct of C#’s keywords class and struct used to declare them. What hasn’t been mentioned yet is why the distinction exists and what precisely that means. This section will explore those questions.

An instance of a reference type, called an object, is allocated and managed on the Garbage Collected (GC) heap, and all reads, writes, and sharing of it are performed through a reference (i.e., a pointer indirection). A value type instance, called a value, on the other hand, is allocated inline as a sequence of bytes, the location of which is based on the scope in which it is defined (e.g., on the execution stack if defined as a local, on the GC heap if contained within a heap-allocated data structure). Values are not managed independently by the GC, and are copied while sharing. They are used to represent the primitive and scalar data types.

To illustrate the difference between sharing an object and sharing a value, for example, consider the following. If you were to "load" a field containing an object reference, you would be loading a shared reference to that object. Conversely, when you "load" a field containing a value, you’re loading the value itself, not a reference to it. Accessing the object will dereference that pointer to get at the shared memory, while accessing the value will work directly with the sequence of bytes making up that value.

There are clear pros and cons to using one or the other based on your usage. For example, System.String is a reference type, while System.Int32 (i.e., int32 in IL, int in C#) is a value type. This was done for a reason. The default choice for you should always be a class; however, whenever you have a small data structure with value semantics, using a struct is often more appropriate. This section seeks to educate you about the fundamental differences between the two, and on the pros and cons. It also covers the concepts of interfaces, pointer types, boxing and unboxing, and the idea of nullability.


Previous_Page_.gif Next_Page_.gif


Personal tools