Sobes.tech
Junior — Middle

How do reference types differ from value types, and how does this affect working with them?

sobes.tech AI

Answer from AI

In C#, there are two main data types: reference types and value types.

  • Value types:

    • Store data directly.
    • Examples: int, double, struct, bool.
    • Assigning copies the value.
    • Stored on the stack (in most cases).
  • Reference types:

    • Store a reference to the memory location where data is held.
    • Examples: class, string, array.
    • Assigning copies the reference, not the data itself.
    • Stored on the heap.

Impact on operation:

  • Changes in a reference type object are reflected in all references to it.
  • Value types are copied when passed to methods, so changes inside the method do not affect the original.
  • Memory management for reference types is handled by the garbage collector.

Example:

int a = 5;
int b = a; // copy of the value
b = 10;
// a remains 5

class Person { public string Name; }
Person p1 = new Person { Name = "Alice" };
Person p2 = p1; // copy of the reference
p2.Name = "Bob";
// p1.Name is now "Bob"