Sobes.tech
Junior — Middle

What is the difference between value objects and reference objects in programming?

sobes.tech AI

Answer from AI

In C#, objects are divided into value types and reference types.

  • Value types store data directly. Examples: int, struct, bool. When assigned or passed to a method, the value itself is copied.
  • Reference types store a reference to the memory area where data resides. Examples: class, string, arrays. When assigned, only the reference is copied, not the object itself.

The main difference is that changes to a value type do not affect other copies, whereas changes through a reference reflect on all references to that object.

Example:

int a = 5;
int b = a; // copies the value
b = 10;
// a == 5, b == 10

class Person { public string Name; }
Person p1 = new Person { Name = "Alice" };
Person p2 = p1; // copies the reference
p2.Name = "Bob";
// p1.Name == "Bob"