Value Type vs Reference Type

Value Type vs Reference Type

The Types in .NET Framework are either treated by Value Type or by Reference Type.

Value Type

A Value Type stores its contents in memory allocated on the stack. When you created a Value Type, a single space in memory is allocated to store the value and that variable directly holds a value.

In C#, all the “things” declared with the following list of type declarations are Value types (because they are from System.ValueType):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bool
byte
char
decimal
double
enum
float
int
long
sbyte
short
struct
uint
ulong
ushort

Reference Types

Reference Types are used by a reference which holds a reference (address) to the object but not the object itself. Because reference types represent the address of the variable rather than the data itself, assigning a reference variable to another doesn’t copy the data. Instead it creates a second copy of the reference, which refers to the same location of the heap as the original value.

All the “things” declared with the types in this list are Reference types (and inherit from System.Object… except, of course, for object which is the System.Object object):

1
2
3
4
5
class
interface
delegate
object
string

By default a class instance as an object is passed to methods by value, to change this if you want the method to alter the object, pass it with the ref keyword.

1
2
3
4
var myObj = new SomeClass();

SomeMethodThatChangesTheObjectValues(ref myObj)
//do something magical

References