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.
using System;
using System.Collections.Generic;
using System.Text;
namespace CSApp1
{
class Shape
{
public int length;
public int width;
public Shape()
{
length = 0;
width = 0;
}
}
// Make struct Rectangle to solve the Null reference exception problem
class Rectangle
{
public Shape MyShape;
}
class MyClass
{
static void Main(string[] args)
{
Rectangle obj1;
obj1.MyShape.length = 100; // will cause System.NullReferenceException
System.Console.WriteLine(obj1.MyShape.length);
}
}
}
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.
|