Primitive types in .Net such as int, float etc are aliases for system objects
such as System.Int32.
In .Net there are two main kinds of types value types and reference types.
A value type is a type where the actual value is stored inside the area of
memory pointed to by the variable:
i.e.
int a = 3
means that "a" is an alias for a memory location which is a 32 bit space
containing the value 3. Value types are stored on the stack (one of the
types of areas of memory allocated to a process), the stack also stores
function parameters when you make a function call and return pointers to
allow the program to know where it needs to jump back to after a function
call.
You will actually see that for a variable of type int, it has the alias
System.Int32, which derives from System.ValueType which derives from
System.Object.
The stack is not always suitable for some kinds of variables because it is
not very persistent, it is always changing and the scope of items on it only
last for the procedure call tree, so another type of variable is needed.
The other main type are reference types. These are objects that do not live
on the stack but in the managed heap, an area of memory that allows variables
to be stored for the entire program execution. Objects living in the heap
can be of any size. This time when you have a variable pointing to an object
the variable does not point directly to the object but it contains the memory
address of the object on the heap
i.e.
MyObject x -> contains -> 32bit number which points to -> address of x on
the heap
You will see that value type can not be null (because they do not point to
memory locations) they must have a value becuase they just store data. So
int x = null is not valid whereas int x = -1 is.
The final piece of the puzzle is boxing/unboxing, the process of boxing is
to turn a value type into a reference type so it can be treated as an object,
unboxing is the opposite process. A simple reason why we may want to do this
is:
int i =3;
i.ToString();
in this case the int is a value type but we want to treat it like an object
with a method called ToString(), in the code above i is being boxed.
When you box one important thing to keep in mind is that the actual value of
the value type is COPIED into the boxed object, and when it is unboxed it is
COPIEd again out of the object, so for example:
int i =1;
object obj = (object)i;
i = i +1;
int j = (int)obj;
print(i);
print(j);
You will see the output 2 : 1 (maybe some people would expect 2 : 2)
This is because when you do object obj = (object)i the value inside is
copied into the obj object when the boxing ocurrs.
Hope this helps answer your question.
Mark.
"luis" wrote:
Are basic types (int, long, ...) objetcs or not?
I read that in C# all are objects including basic types, derived from Object
class. Then in msdn documentation says that boxing converts basic types in
objects. But if they are objects why it´s need this conversion? Aren´t
objects (basic types) like Java?