O'Reilly logo

C# Language Pocket Reference by Ted Neward, Ben Albahari, Peter Drayton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Value and Reference Types

All C# types fall into the following categories:

  • Value types (struct, enum)

  • Reference types (class, array, delegate, interface)

The fundamental difference between the two main categories is how they are handled in memory. The following sections explain the essential differences between value types and reference types.

Value Types

Value types directly contain data, such as the int type (which holds an integer) or the bool type (which holds a true or false value). The key characteristic of a value type is a copy made of the value that is assigned to another value. For example:

using System;
class Test {
  static void Main ( ) {
    int x = 3;
    int y = x; // assign x to y, y is now a copy of x
    x++; // increment x to 4
    Console.WriteLine (y); // prints 3
  }
}

Reference Types

Reference types are a little more complex. A reference type defines two separate entities: an object and a reference to that object. This example follows the same pattern as our previous example, except that the variable y is updated here, while y remained unchanged earlier:

using System;
using System.Text;
class Test {
  static void Main ( ) {
    StringBuilder x = new StringBuilder ("hello");
    StringBuilder y = x;
    x.Append (" there");
    Console.WriteLine (y); // prints "hello there"
  }
}

This is because the StringBuilder type is a reference type, while the int type is a value type. When we declared the StringBuilder variable, we were actually doing two different things, which can be separated into these two ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required