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

C# Tutorial - About Value Types and Reference Types

By David Bolton, About.com

1 of 10

About Value Types and Reference Types

Memory Use

Value and Reference Types

If you know C and C++ then you'll be familiar with the difference between local or auto variables and pointer/reference variables that are created on the heap. It's similar for C# value types and reference types.

The Heap and The Stack

Procedural programming languages that let you to create variables dynamically at run-time use two different areas of Ram for holding variables;. the stack and the heap. The heap is basically all unallocated memory.

The picture shows a rough layout of a program in memory. The first four areas (Program Code, Static Data, Uninitialized Data and Stack) are fixed in size when the application is linked and the heap is what's left over.

This is for each application, but because of the way a CPU virtualizes memory, each application runs in its own space and sees itself as having access to all available ram.

The stack holds value type variables plus return addresses for functions. All numeric types, ints, floats and doubles along with enums, chars, bools and structs are value types.

The heap hold variables created dynamically- known as reference variables and mainly instances of classes or strings. These variables are stored in two places; there's a hidden pointer to the place in the heap where the data is stored.

Another distinction between value and reference type is that a value type is derived from System.ValueType while a reference type is derived from System.Object.

If you assign a value type variable to another then a direct copy of the value is made. But copying a reference type variable just makes a copy of the reference to the variable and does not affect the variable itself. This is like pointers in C and C++. You aren't copying what the pointer points to but making a copy of the pointer itself.

On the next page : All about Structs

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

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

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. C# Tutorial - About Value Types and Reference Types>

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

All rights reserved.