Wednesday, 27 October 2010

C# Reference and Value Type Examples

//Create an instance of a class and a structure
//(definitions for these classes are not shown in this source code)
SpangeClass spangeClassOne = new SpangeClass(); //reference type
SpangeStruct spangeStructOne = new SpangeStruct(); //value type

//set fields
spangeClassOne.FirstName = "Andrew";
spangeClassOne.LastName
= "Strauss";
spangeStructOne.FirstName
= "Graeme";
spangeStructOne.LastName
= "Swann";

//return all fields
MessageBox.Show(string.Format("{0} {1} and {2} {3}",
spangeClassOne.FirstName,
spangeClassOne.LastName,
spangeStructOne.FirstName,
spangeStructOne.LastName));

//make copies of both
SpangeClass spangeClassTwo = spangeClassOne;
SpangeStruct spangeStructTwo
= spangeStructOne;

//set fields on copies to show how
//fields on the class (reference type) will update the original where as
//fields on the struct (value type) will not update the original
spangeClassTwo.FirstName = "Ricky"; //this updates the original as well (reference type)
spangeClassTwo.LastName = "Ponting";//Because second instance of the class is given a new area
//of the heap but not a new area of the stack.
//Both bits of heaps are pointing at the same bit of stack
spangeStructTwo.FirstName = "Nathan"; //this does not update the original as well (value type)
spangeStructTwo.LastName = "Hauritz"; //Because both structs are in seperate areas of the stack

MessageBox.Show(
string.Format("{0} {1} (changed - reference type) and {2} " +
"{3} (did not change - value type)",
spangeClassOne.FirstName,
spangeClassOne.LastName,
spangeStructOne.FirstName,
spangeStructOne.LastName));

//a simpler example with an array (reference) and ints (value)

//originals
string[] TestArray = new string[10];
TestArray[
1] = "Original Array Value";
int TestInt = 99;

//copies
//Array update will alter the original where as
//int update will only alter the copy and not the original, so we don't see 42
string[] TestArrayCopy = TestArray;
TestArrayCopy[
1] = "New Array Value"; //this updates the original as well (reference type)
int TestIntCopy = TestInt;
TestIntCopy
= 42; //this does not update the original as well (value type)

MessageBox.Show(TestArray[
1]);
MessageBox.Show(TestInt.ToString());