Value Types
Value types include the following:

  • All numeric data types
  • Boolean, Char, and Date
  • All structures, even if their members are reference types
  • Enumerations, since their underlying type is always SByte, Short, Integer, Long, Byte, UShort, UInteger, or ULong

Reference Types
Reference types include the following:
  • String
  • All arrays, even if their elements are value types
  • Class types, such as Form
  • Delegates

Elements That Are Not Types
The following programming elements do not qualify as types, because you cannot specify any of them as a data type for a declared element:
  • Namespaces
  • Modules
  • Events
  • Properties and procedures
  • Variables, constants, and fields



An example

This example shows the difference between how a value type works in memory, and how a reference does. First we define a new Value Type and a new Reference Type.
class ReferenceType
{
   public Int32 X;
} 

 
struct ValueType
{
   public Int32 X;
}
Now we want to use these types to show how they work:
ReferenceType ref1 = new ReferenceType();

ValueType val1     = new ValueType()
 
ref1.X = 5
val1.X = 5;
The layout of the memory at this point looks something like the following:

 If we now make copies of these values using the following code:
ReferenceType ref2 = ref1;
ValueType val2 = val1;
The layout of the memory now looks something like the following:
 If we now change the value of each of the new copies using the following code:
Ref2.X = 8;
Val2.X = 8;
The layout of the memory now looks something like the following:
Summary
  • A variable that is of type value directly contains a value. Assigning a variable of type value to another variable of type value COPIES that value.
  • A variable of type reference, points to a place in memory where the actual object is contained. Assigning a variable of type reference to another variable of type reference copies that reference (it tells the new object where the place in memory is), but does not make a copy of the object.

  • Value types are stored on the stack.
  • Reference types are stored on the heap.

  • Value types can not contain the value null. *
  • Reference types can contain the value null.

  • Value types have a default implied constructor that initializes the default value.
  • Reference types default to a null reference in memory.

  • Value types derive from System.ValueType.
  • Reference types derive from System.Object.

  • Value types cannot derive a new type from an existing value type, but they are able to implement interfaces.
  • Reference types can derive a new type from an existing reference type as well as being able to implement interfaces.

  • Changing the value of one value type does not affect the value of another value type.
  • Changing the value of one reference type MAY change the value of another reference type.

  • The nullable type (only in .NET 2.0) can be assigned the value null.








0 comments: