You have selected free tutorial of the Microsoft Corporation for the Microsoft Technology Associate (MTA) :
98-361: MTA: Software Development Fundamentals (C#) : Module 1: Introduction to Programming :
UNDERSTANDING DATA TYPES
there are two types of predefined data types:
n Value types—These store the value directly. Data types such as int, float, double,
bool, and char are value types that are stored on the stack.
n Reference types—These data types don’t store the value; instead, they store a
reference to the value. The class objects, strings, and dynamically created variables
are known as reference types because they hold references to blocks of memory
and are managed on the heap. The heap is basically all unallocated memory in an
operating system. When you declare a variable, the compiler allocates a block of
memory to store a corresponding value.
The following example makes it clearer:
int l=50;
int b=l;
Because the variable l is an int data type, 4 bytes of memory will be allocated for it.
The value 50 that is assigned to the variable l is stored in the allocated block of memory.
For the variable b, a separate block of 4 bytes of memory is allocated, and its value
of 50 is stored in another memory block. The value of 50 is stored in two locations in
memory; consequently, the changes made in either variable do not affect the other.
For example, if the value of variable l is incremented by 5:
l+=5
then only the memory block of variable l is updated to show the new value of 55.
There is no change in the block of memory assigned to variable b.
Now consider the following example of a reference type. Assume that Rect is a class
with two member variables: length and breadth.
Rect r=new Rect(50,8);
Rect s=r;
The values 50 and 8 are assigned to the member variables length and breadth of the
object r. Remember: only one Rect object, r, is created. r and s point to the same memory
location that contains the object. As reference types, the variables r and s just contain
a reference; that is, they refer to the same object. The value of one object displays
in another, and the changes made in either object affect the other. Because values
50 and 8 were assigned to the member variables length and breadth, the following
example displays the value of member variable length (50):
Console.WriteLine(s.length);
Similarly, after you change the value of the member variable, the length of object s also
makes the changes in the member variable of object r:
s.length=70;
Console.WriteLine(r.length);
The garbage collector claims the memory allocated to the reference types when there
are no references left for them. Similarly, when the value types go out of scope, the
memory allocated to them is released. Using value types increases performance
because fewer objects on the managed heap reduce overloading of the garbage
collector.
|