What is the difference between Value Types and Reference Types

In C#, data types are classified into two categories: Value Types and Reference Types. Understanding the difference between these two types is crucial for effective programming.

Value Types

Value types hold the actual data. When you assign a value type to another variable, a copy of the value is made. Common value types include:

  • Integers (e.g., int, long)
  • Floating-point types (e.g., float, double)
  • Boolean (e.g., bool)
  • Structs (e.g., struct)

Example of Value Type:

int a = 10; int b = a; // Copy of 'a' is made b = 20; // Changes 'b' only, 'a' remains 10

Reference Types

Reference types store a reference to the memory address where the data is located. When you assign a reference type to another variable, both variables will refer to the same data. Common reference types include:

  • Strings (e.g., string)
  • Arrays (e.g., int[])
  • Classes (e.g., class)
  • Interfaces (e.g., interface)

Example of Reference Type:

class Person { public string Name; } Person person1 = new Person(); person1.Name = "Alice"; Person person2 = person1; // Reference to the same object person2.Name = "Bob"; // Changes name for both person1 and person2

Value Types Reference Types C# Data Types Value Type Example Reference Type Example