Figure 1
Base Class Library Types
C# Primitive Type | BCL Type | Description |
sbyte | System.SByte | Signed 8-bit value |
byte | System.Byte | Unsigned 8-bit value |
short | System.Int16 | Signed 16-bit value |
ushort | System.UInt16 | Unsigned 16-bit value |
int | System.Int32 | Signed 32-bit value |
uint | System.UInt32 | Unsigned 32-bit value |
long | System.Int64 | Signed 64-bit value |
ulong | System.UInt64 | Unsigned 64-bit value |
char | System.Char | 16-bit Unicode character |
float | System.Single | IEEE 32-bit float |
double | System.Double | IEEE 64-bit float |
bool | System.Boolean | A True/False value |
decimal | System.Decimal | 96-bit signed integer times 100 through 1028 (common for financial calculations where rounding errors can't be tolerated) |
object | System.Object | Base of all types |
string | System.String | String type |
Figure 2 Reference Types versus Value Types // Reference Type (because of 'class')
class RectRef { public int x, y, cx, cy; }
// Value type (because of 'struct')
struct RectVal { public int x, y, cx, cy; }
static void SomeMethod {
RectRef rr1 = new RectRef(); // Allocated in heap
RectVal rv1; // Allocated on stack (new optional)
rr1.x = 10; // Pointer dereference
rv1.x = 10; // Changed on stack
RectRef rr2 = rr1; // Copies pointer only
RectVal rv2 = rv1; // Allocate on stack & copies members
rr1.x = 20; // Changes rr1 and rr2
rv1.x = 20; // Changes rv1, not rv2
}
Figure 3 Boxing // Declare a value type
struct Point {
public int x, y;
}
static void Main() {
ArrayList a = new ArrayList();
for (int i = 0; i < 10; i++) {
Point p; // Allocate a Point (not in the heap)
p.x = p.y = i; // Initialize the members in the value type
a.Add(p); // Box the value type and add the
// reference to the array
}
}
Figure 4 Manually Boxing Value Types public static void Main() {
Int32 v = 5; // Create an unboxed value type variable
// When compiling the following line, v is boxed 3 times
// wasting heap memory and CPU time
Console.WriteLine(v + ", " + v + ", " + v);
// The lines below use less memory and run faster
Object o = v; // Manually box v (just once)
// No boxing occurs to compile the following line
Console.WriteLine(o + ", " + o + ", " + o);
}