Author: Kristofer Gäfvert
First Published: January 23, 2005
Last Updated: January 23, 2005
Last Reviewed: January 23, 2005
PDF: N/A
Download Code: CSharpDataTypes-Code.zip
Table of Contents
Introduction
Value Types
Reference Types
C# provides a set of different data types. The data types in C# are divided into two categories – Value Types and Reference Types. Although there is a third data type – pointers, I will not discuss it here. Pointers can only be used in unsafe code, and as you can figure out by the name, it is not safe and if you can avoid using unsafe code, do it!
A variable that is a value type, stores the data, while a variable of a reference type stores a reference to the data.
Both Value Types and Reference Types have one interesting thing in common – they both derive from System.Object. This is interesting, because most other object oriented languages does not have this behavior. C# is however not the first language, Smalltalk is another language where all objects are derived from a single base class.
The value of value types are stored on the managed stack, and can be used directly. This means that the value is stored, and not a reference to the value. This also means that each value type has its own copy of the data. Reference Types on the other hand has a reference to the data, and several variables can reference the same data.
using System;
class TestValueTypes
{
public static void Main()
{
int a = 5;
int b;
b = a;
Console.WriteLine("a = " + a + "\nb = " + b);
a++;
Console.WriteLine("We have now increased a with 1");
Console.WriteLine("a = " + a + "\nb = " + b);
}
}
Output:
a = 5 b = 5 We have now increased a with 1 a = 6 b = 5
To compile this code (if you downloaded it), type:
csc ValueTypes.cs
The above code shows that all value types are working with each own data. The variables “a” and “b” do not reference the same data, “b” just happen to copy the value of “a”. If we draw a picture of this, it would look like this:

Memory for variables allocated on the managed stack is automatically freed when they go out of scope.
Value types always have a value. It might be zero (0), but zero is also a value. For all simple value types, the default value is the value produced by a bit pattern of all zeros. So for sbyte, byte, short, ushort, int, uint, long and ulong the default value is 0. For float it is 0.0f, and for bool it is false. Section 4.1.2 in the C# Language Reference lists all the default values for the value types. The “value” of a value type cannot be null. That is, value types always have a value.