1. Home
  2. Computing & Technology
  3. C / C++ / C#

C# Tutorial - About Value Types and Reference Types

By , About.com Guide

4 of 10

Working with Reference Types

The main reference type is object which is an instance of a class. The other one is string.

The constructor for a reference type allocates memory in the heap and then supplies a reference to this. C# hides the underlying details and prevents the possibility of C/C++ null pointer problems.

However, unlike a value type, a reference type can be null.

Download Example 3

But the compiler will usually stop you doing silly things. Objects in C# are generally easier to work with than in C++.

using System;

namespace ex1
{

  class test
  {
      public int a = 9;
  }

  class ex1
  {
      static void Main(string[] args)
      {
      test t=null;
          t.a = 5;
          Console.ReadKey() ;
      }
  }
}

This compiles and runs, up to the t.a = 5; assignment where it falls over as t is null. The = null makes the compiler happy that t has a value, even if at runtime it's not valid. Try removing the = null and the compiler will flag the error.

On the next page : Reference versus Value Types- Which to use?

Explore C / C++ / C#
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. Working with Reference Types

©2009 About.com, a part of The New York Times Company.

All rights reserved.