Variables and Standard Types

Value types vs. Reference types

The .NET Framework supports the concept of value and reference types. This classification is essentially a notation of whether a type stores its own value, or a reference (pointer) to its value.

 

Value types

A value type is also known as a struct in C#. A value type stores its value in its own allocation of memory.

A value type must have a value and cannot be set to null, representing no value. For this reason, when you declare a value type variable without an initializer, it is implicitly initialized with the type's default value:

int number; // Number is implicitly set to 0, or default(int)

When you pass a value type to a method, you are in essence cloning the value, so any changes you make to your variable in your method, will not be reflected in your original variable

using System; public class Program...

 

This is known as 'pass by value'.

Useful Tip

All numeric types, booleans, dates/times, any type that is declared as a struct and enums are all value types.

 

Reference types

A reference type is one that does not store its value directly, instead it stores a reference to another location in memory.

A reference type can be set to null, and when you pass a reference type to a method, because you are passing the reference to the value, not the value itself, and changes you make in your methods, will affect the original variable:

using System; public class Program...

 

Useful Tip

All other types, including the root Object type are reference types, and are declared as classes.

 
 

You will find out more about the importance of value and reference types in later tutorials.

 

Page 7 of 17