Types in the .NET Framework – Part 2: Reference Types

<Part1: Value Types  ^Exam 70-536 Topics^  Next Topic>

Reading notes from MCTS Self-Paced Training Kit (Exam 70-536): Microsoft® .NET Framework 2.0—Application Development Foundation.

Chapter 1 Framework Fundamentals

Lesson 2: Using Common Reference Types

Difference between value types and reference types:

  • Reference types store a pointer to their data on the stack, the pointer is the address where the data is stored in the section of memory referred to as the heap. The .NET Framework runtime performs garbage collection on data in the heap that no longer is referenced by a pointer on the stack.NOTE: Garbage collection is optimized for programs in which most objects are short lived, except those allocated at the beginning of the application.
  • Value types and reference types differ when assigning values by: Assigning one reference type variable to another doesn’t copy the data. Both variables end up pointing to the same data instead.

Built-in reference types:

There are about 2,500 in the .NET Framework. Anything not derived from System.ValueType is a reference type.  Many of the reference types are derived from these commonly used reference types:

  • System.Object – The most general type in the .NET Framework. You can convert any type to System.Object.
  • System.String – Text data.
  • System.Text.StringBuilder – Dynamic text data.
  • System.Array – The base class for all arrays.
  • System.IO.Stream – Buffer for file, device, and network I/O.
  • System.Exception – Handles system and application defined exceptions and is the base class for task-specific exceptions.

The StringBuilder:

String types are immutable in .NET, this means that when a string is changed, the runtime creates a new one and abandons the old one. Applications run more efficiently (temporary, abandoned strings are not created) if you use String.Concat, .Join, or .Format in a single statement instead of operators like +. Use the StringBuilder type to .Append, .Insert, .Remove, or .Replace parts of a string across multiple statements. StringBuilder also overrides the operators:

  • Concatenation:         + or &  
  • Test for equality:     =
  • Test for inequality:  <>
  • Assignment:              =

Creating and sorting arrays:

  • Array declaration: Dim BBArray() as Integer = (5, 3, 7)
  • Sort an array using a shared (static) method: Array.Sort(BBArray)
  • Accessing and displaying array elements: Console.WriteLine("{0}, {1}, {2}", BBArray(0), BBArray(1), BBArray(2)) ' Output will be: 3, 5, 7

Using streams:

Streams are used to communicate with the console, network, disk, etc. Common stream types that inherit from System.IO.Stream are:

  • FileStream – used to write to, and read from files.
  • MemoryStream – used to write to, and read from memory.
  • StreamReader – used to read data from a stream.
  • StreamWriter – used to write date to a stream

StreamReader and StreamWriter are the simplest stream classes to use.

  • StreamWriter can be used to open and write to a file as shown below:
    Imports System.IO Dim BBsw As StreamWriter = New StreamWriter("BBfile.txt") BBsw.WriteLine("Hi there world!") BBsw.Close
  • StreamReader can be used to open and read from a file like this:
    Dim BBsr As StreamReader = New StreamReader("BBfile.txt") Console.WriteLine(BBsr.ReadToEnd) BBsr.Close

Detecting and responding to exceptions:

Exceptions (unexpected events) can come from the system. For example, if your application trys to write to a drive with a removable disk that is full, write protected, or has been removed from the drive, then an exception will be thrown by the system. Your application should catch and handle this exception rather than crash. In the example below, any kind of error will cause the code in the Catch block to be executed (in this case it prints an error message), otherwise, it is skipped.

    Dim BBsr as StreamReader = New StreamReader("C:BBfile.txt") 
Catch ex As Exception 
    Console.WriteLine("Error reading file: " + ex.Message) 
End Try

In addition to the base Exception class there are hundreds of exception classes that are derived from System.SystemException that describe all kinds of system events. You can also define exceptions for events that might occur in your application by deriving from System.ApplicationException. It is useful to respond to different exceptions in different ways. You can use multiple catch blocks in your code, ordered from most specific to most general. The first catch block with a matching exception will be executed, the rest will be skipped. (This is sometimes called filtering exceptions). The example below also includes a Finally block. This block is executed whether an exception is caught or not. Also, notice that BBsr is declared outside the Try block so that it will be in scope for the code in the Finally block. Note that Try, Catch, Finally blocks can be nested.

Dim BBsr as StreamReader = New StreamReader("C:BBfile.txt") 
Catch ex As System.IO.FileNotFoundException 
    Console.WriteLine("The file could not be found") 
Catch ex As System.IO.UnauthorizedAccessException 
    Console.WriteLine("You do not have permission to write to this file") 
Catch ex As Exception 
    Console.WriteLine("Error reading file: " + ex.Message) 
End Try

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed

%d bloggers like this: