Value types compared with reference types
Some variables hold a value directly. Others hold a reference to a value stored elsewhere. Copying them behaves differently, and that catches people out.
Copy a value
C#
int a = 5;
int b = a; // b gets its own copy
b = 9; // a is still 5
Lesson one = new Lesson();
Lesson two = one; // both point at the same object
two.Title = "Changed"; // one changes tooWhat to remember
- Simple values such as numbers and booleans copy independently.
- Objects are reached through a reference, so two names can point at one object.
- Changing the object through either name is visible through both.
When this bites. Passing an object to a method lets that method change your object. Sometimes that is what you want. When it is not, pass a copy or return a new object instead.
Exposing object data safely is the subject of properties.