Monday, 29 January 2007

Common Reference Types

Most types within the .NET Framework are reference types, in fact about 2500 reference types are available. Reference type store the address of the data in the stack, also known as a pointer & the actual data of the object is stored on the heap. When no more pointers point to the data on the heap the object is eligable for garbage collection.

Garbage collection will only occur when needed or when triggered by a call to GC.Collect. Automatic garbage collection is optimised for applications where most instances are short-lived, except for those allocated at the beginning of the application.

Everything not derieved from System.ValueType is a reference type, the most commonly used reference types are listed below.


  • System.Object
  • System.String
  • System.Text.StringBuilder
  • System.Array
  • System.IO.Stream
  • System.Exception

Reference types are more than containers for data, they provide means to manipulate their members, System.String provides a set of members for working with text.

System.String class in .NET is immutable, meaning changes to a string instance causes the runtime to create a new string instance and abandon the old one. This happens behind the scenes this has the following implications.

string s = "first entry";    
s += " second entry";
s += " third entry";
s += " fourth entry";
Only the last string has a reference, the first three entries will be disposed of  during garbage collection.  To avoid unnecessary garbage collection you can do one of several things.
  • Use the String class's Concat, Join, or Format methods to join multiple items in a single statement
  • Use the StringBuilder class to create dynamic (mutable) strings.

The System.Array class can be used to Sort items, as with the System.String type, System.Array provides members for working with its contained data.

int[] a = {3, 5, 6, 4 };
Array.Sort(a);
Streams are another very common type they provide a means for reading and writing to the disk and communicating across the network.  The System.IO.Stream type is the base type for all task specific stream types.  The most common stream classes are shown below.
FileStream
Create a base stream used to write or read from a file
MemoryStream
Create a base stream used to write or read from memory
StreamReader
Read data from the stream
StreamWriter
Write data to the stream
Simplest of the stream classes is the StreamReader & StreamWriter classes.  You can pass a filename to the constructor enabling you to read or write to a file.  After processing the file you call the Close method on the stream to release the lock on the file.

 
StreamReader sr = new StreamReader(filename);
Console.WriteLine(sr.ReadToEnd());
sr.Close();

No comments: