Sobes.tech
Junior — Middle

Can you explain how reference data types differ from value types in C#?

sobes.tech AI

Answer from AI

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

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

Example:

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

class Person { public string Name; }
Person p1 = new Person { Name = "Alice" };
Person p2 = p1; // p2 and p1 refer to the same object
p2.Name = "Bob"; // now p1.Name is also "Bob"

Thus, changes in reference types through one variable are reflected in all references, while in value types they are not.

Can you explain how reference data types differ from… - sobes.tech