Intern / FresherC#

What is the difference between a value type and a reference type in C#?

Quick answer

A value type variable holds its data directly and is copied on assignment, while a reference type variable holds a reference to an object, so assignment copies the reference and both variables see the same object.

Value types include int, double, bool, char, DateTime, enums and any struct. Reference types include class, string, arrays, delegates and object. A value type is stored inline where it is declared: on the stack for a local variable, or inside the containing object on the heap. A reference type's object always lives on the managed heap and is cleaned up by the garbage collector.

This changes behaviour when you pass values to methods. Passing a struct hands the method its own copy, so changes inside do not leak out. Passing a class passes a copy of the reference, so the method can modify the same object. Reference types can be null; value types cannot, unless you use Nullable<T> (int?).

struct PointS { public int X; }
class PointC { public int X; }

var s1 = new PointS { X = 1 }; var s2 = s1; s2.X = 99;
Console.WriteLine(s1.X);   // 1  (copy)

var c1 = new PointC { X = 1 }; var c2 = c1; c2.X = 99;
Console.WriteLine(c1.X);   // 99 (same object)

Key points

  • Value types are copied, reference types share one object
  • Reference types can be null, value types need int? syntax
  • Large mutable structs are usually a bad idea

Questions interviewers ask next