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 ...
Get C# Language Pocket Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.