C# - Difference Between Value and Reference Type
Numeric data types such as integers, floats, etc, boolean, enumerations and user defined structures are value types.
Classes, interfaces and delegates are reference types.
Object, string, dynamic are the built in reference types.
The following code will perfectly compile but will cause error at run time - System.NullReferenceException. It might be new for C++ programmers and this would be a good example to understand the value type and reference type.
public int length;
public int width;
length = 0;
width = 0;
// Make struct Rectangle to solve the Null reference exception problem
public Shape MyShape;
static void Main(string args)
obj1.MyShape.length = 100; // will cause System.NullReferenceException
You can solve this exception problem in two ways:
- Make the Shape class as struct. so that it becomes value type.
- Add this line obj1.MyShape = new Shape();after defining Rectangle obj1.