Sobes.tech
Junior

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

sobes.tech AI

Answer from AI

Reference types store the address in memory where the data resides. Value types store the data itself directly in the variable.

Reference types:

  • Inherit from System.Object.
  • Located on the heap.
  • When assigning a reference type variable to another, the reference to the data is copied, not the data itself.
  • Initialized to null by default.
  • Include classes (class), interfaces (interface), delegates (delegate), arrays (array), strings (string).

Value types:

  • Inherit from System.ValueType (which in turn inherits from System.Object).
  • Located on the stack or inside an object if they are fields of a reference type.
  • When assigning a value type variable to another, the data itself is copied.
  • Initialized to zero or default values (0 for numbers, false for bool, empty for struct) by default.
  • Include structs (struct), enums (enum), built-in data types (int, float, bool, etc.).

Example:

// Reference type
public class MyClass
{
    public int Value;
}

// Value type
public struct MyStruct
{
    public int Value;
}

// Usage
MyClass obj1 = new MyClass { Value = 10 };
MyClass obj2 = obj1; // obj2 and obj1 refer to the same object in the heap
obj2.Value = 20; // Change through obj2 affects obj1
Console.WriteLine(obj1.Value); // Will output 20

MyStruct s1 = new MyStruct { Value = 10 };
MyStruct s2 = s1; // Data is copied, s2 is an independent copy
s2.Value = 20; // Change through s2 does not affect s1
Console.WriteLine(s1.Value); // Will output 10