Saturday 22 March 2008

Value Types


Stack and Heap

Before explaining value types, I think it is necessary to have a brief overview of memory.

There are two main types of memory types Stack and Heap (I'm sure the purists amongst you will explain that this is not the case and become very technical about it; however for this discussion of types it will suffice)

So what is the difference between the two.

Matthew Cochran has an excellent article to explain the difference, and is worth reading through.

C# Heap(ing) Vs Stack(ing) in .NET:

Value Types

If you have read Matthews article you will know that Value Types are stored on the Stack.

Lets take a look at the three general types

  • Built in types
  • User-defined types
  • Enumeration types
Built in types

These are types that are provided by the .NET Framework. All built in numeric types are value types, examples are:

Type C# alias
System.SByte sbyte
System.Byte byte
System.Int16 short
System.Int32 int
System.Uint32 uint
System.Int64 long
System.Single float
System.Double double
System.Decimal decimal
System.Char char
System.Boolean bool
System.IntPtr - N/A -
System.DateTime date

 

The above table shows the most common value types, there are over 300 others not listed here in the .NET Framework.

Declaring a value type

int i = 0;
bool b = false;


/*
New to .NET 2 is Nullable option.
This allows you to set an integer or a boolean for example to not assigned
*/
Nullable<bool> b = null;

// This can also be written as
bool? b = null;



 Once a value has been declared as Nullable you can then use the HasValue  and Value members.


if (b.HasValue)

{


    lblMessage.Text = string.Format("b is {0}", b.Value);


}



 



User-defined Types (Structures / Struct)



Structures behave similar to Classes except the values are stored on the stack. Structures are built from other value types. For example you may have a Struct that you would use for ExamDates.



protected void Page_Load(object sender, EventArgs e)
{



    DateTime MyStartDate = DateTime.Now;

ExamDates MyExam = new ExamDates(MyStartDate);
lblMessage.Text = MyExam.ToString();

}



struct ExamDates
{
DateTime startDate;
public ExamDates(DateTime _startDate)
{
_startDate = _startDate.AddDays(30);
startDate = _startDate;
}
public override string ToString()
{
return string.Format("The exam date is {0}", startDate);
}
}


 



What the above does is create a user-defined type of ExamDates that takes one parameter of a start date of the exam. 30 Days are added to the start date to get the exam date. We have overridden the ToString() method  so that it always returns text about the exam date.



Enumerator Types



Enumerators are used to supply a list of choice. For example for an enumerator that uses the type of exam we are doing, we could use the following



// C#



enum Courses : int { MCTS_70536, MCTS_70528, MCPD_70547};



Courses MyCourse = Courses.MCPD_70547;

No comments: