Junior — Middle
Can you explain the differences between value and reference data types?
sobes.tech AI
Answer from AI
Value types and reference types differ in the way they store and pass data.
-
Value types (e.g., structures in C#) store data directly. When assigned or passed, a copy of the data is created. Changes to the copy do not affect the original.
-
Reference types (e.g., classes in C#) store a reference to the memory location where the data is held. When assigned, the reference is copied, not the data itself. Changes through one reference are reflected in all references pointing to the same object.
Example:
struct Point {
public int X, Y;
}
class Person {
public string Name;
}
Point p1 = new Point { X = 1, Y = 2 };
Point p2 = p1; // copy
p2.X = 3;
// p1.X is still 1
Person person1 = new Person { Name = "Alice" };
Person person2 = person1; // reference copy
person2.Name = "Bob";
// person1.Name is now "Bob"
Thus, the choice between value types and reference types affects the program's behavior when copying and modifying data.