Tuesday, March 18, 2008

Reference & Value Types and Primitive Types

Value types:
All numeric data types
Boolean, Char, and Date
All structures, even if their members are reference types
Enumerations, since their underlying type is always Byte, Short, Integer, or Long

Reference types:
String
All arrays, even if their elements are value types
Class types, such as Form
Delegates

Primitive types:
Some of the data types are used very frequently during programming. To ease coding using these data types, compilers allow us to usesimplified syntax.
So, the data types supported directly by the compiler are called primitive types and these types map to the types in the Base Class Library (BCL).

For instance, instead of initializing an integer like this;
System.Int32 i = new System.Int32(10); //Throws compiler error

we can easily initialize it using below line of code:
int i =5;

So, the primitive type "int" maps to "System.Int32" type in the BCL.
string maps to System.String.
object maps to System.Object.
...

Boxing & Unboxing:
Boxing refers to the operation of converting a value type to a reference type.

Int32 v = 5; // Create an unboxed value type variable
Object o = v; // o refers to a boxed version of v
v = 123;

-----------------------------------------------------------
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);
}

default Keyword in Generic Code:
This is an issue with the generics concept in .NET 2.0.

public class GenericList
{
}

When we do not know in advance,
whether the type T is a value or a reference type
and if it is a value type whether is it a numeric value or a struct
we can use the default keyword.

T theTypeInstance= default(T);

This initializes theTypeInstance;
to null if T is a reference type,
to 0 if numeric,
the references types of the struct to null & the numeric types of the struct to 0.

References:
http://msdn2.microsoft.com/en-us/magazine/cc301569.aspx
http://msdn2.microsoft.com/en-us/magazine/bb984984.aspx
http://msdn2.microsoft.com/en-us/library/xwth0h0d(VS.80).aspx

No comments: