Value Types and Reference Types in .net

I was reading about Value types and Reference Types for the exam 70-536 which I will be giving soon and there were certain things that I already knew already but some of them were new to me and hence I thought I would have a summary post of what I understand of value types and reference types in .net.

Value Type:

The .net CLR(Common Language Runtime) store the data of the value types in a part of the memory called as the stack. The most basic type of variables like Integers, Booleans, Bytes etc are stored as value types by the .net runtime. Value types can be easily created, updated and removed from the stack by the .net runtime.
There are three types of value types:
•    The built-in types of the .net framework
•    The user defined types
•    Enumerations.

Reference Types:

The .net CLR stores reference types in 2 steps; firstly the address of the memory location, called as a pointer is stored in the stack. This pointer points to the address where the actual data is stored in the part of the memory called as the heap. Reference types which are no longer referenced are garbage collected periodically by the runtime. Reference types are generally very effective in passing parameters to functions.

Some of the examples of reference types include strings, objects (of classes; built-in or otherwise) etc. To illustrate more, I did an experiment which demonstrates value type and reference type and how can it be detected if a variable is a value type or a reference type.

SByte a = 0;
Byte b = 0;
Int16 c = 0;
Int32 d = 0;
Int64 e = 0;
string s = “”;
Exception ex = new Exception();
object[] types = { a, b, c, d, e, s, ex };
foreach (object o in types)
{
string value = “”;
if (o.GetType().IsValueType)
{
value = “Value type”;
}
else
{
value = “Reference type”;
}
Console.WriteLine(”{0},{1}”, o.GetType(), value);
}

In my next post, I will write about how to create your own value type and an example of a reference type used for function calls.

This entry was posted in .NET and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Comment

  1. Posted May 28, 2009 at 7:54 pm | Permalink

    Thanks for writing, I really enjoyed reading your latest post. I think you should post more often, you clearly have talent for blogging!

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>