EasyConcept

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

Technology:
C#
Experience:
Intern,
Junior

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.

Detailed explanation

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?).

Example

csharp
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

Follow-up questions

  • C#Easy

    What is the difference between string and StringBuilder in C#?

    A string is immutable, so every change creates a new string object, while StringBuilder is a mutable buffer that modifies its contents in place, making it much faster for repeated concatenation.

    Intern 路 Junior 路 Performance
  • C#Easy

    What is the difference between const and readonly in C#?

    A const is a compile-time constant that must be assigned where it is declared, while a readonly field can be assigned at declaration or in the constructor, so its value can be decided at runtime.

    Junior 路 Mid-level 路 Programming Fundamentals
  • C#Medium

    How does garbage collection work in C# and when should you use IDisposable?

    The .NET garbage collector automatically frees managed objects that are no longer reachable, organising them into generations 0, 1 and 2 so short-lived objects are collected cheaply, and IDisposable is used to release unmanaged resources such as files and connections promptly.

    Mid-level 路 Senior 路 Memory Management