Understanding value types and reference types helps you know how data is stored and changed in your program.
0
0
Value types vs reference types mental model in C Sharp (C#)
Introduction
When you want to store simple data like numbers or small groups of data.
When you want to work with objects that can be shared and changed by different parts of your program.
When you want to avoid unexpected changes by copying data instead of sharing it.
When you want to understand why changing one variable might affect another.
When you want to write efficient code by choosing the right type for your data.
Syntax
C Sharp (C#)
valueType variable = value;
referenceType variable = new referenceType();Value types hold the actual data directly.
Reference types hold a reference (like an address) to the data stored elsewhere.
Examples
Integers are value types. Changing b does not change a.
C Sharp (C#)
int a = 5; int b = a; b = 10; // a stays 5
Person is a reference type. p1 and p2 point to the same object.
C Sharp (C#)
class Person { public string Name; } Person p1 = new Person(); p1.Name = "Alice"; Person p2 = p1; p2.Name = "Bob"; // p1.Name is now "Bob"
Sample Program
This program shows how value types and reference types behave differently when copied and changed.
C Sharp (C#)
using System; class Program { static void Main() { int x = 10; int y = x; y = 20; Console.WriteLine($"x = {x}, y = {y}"); Person person1 = new Person(); person1.Name = "John"; Person person2 = person1; person2.Name = "Jane"; Console.WriteLine($"person1.Name = {person1.Name}, person2.Name = {person2.Name}"); } } class Person { public string Name; }
OutputSuccess
Important Notes
Value types include int, double, bool, structs, and enums.
Reference types include classes, arrays, delegates, and strings (strings are special but behave like reference types).
Changing a reference type variable affects all references to the same object.
Summary
Value types store data directly and copying them creates independent copies.
Reference types store a reference to data, so copying them shares the same data.
Understanding this helps avoid bugs and write clearer code.