Skip to main content
CSharpUniversity ASP.NET and C# lessons

The search runs entirely in your browser over the published lesson list.

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 too

What 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.

New lessons by email

Leave your address and get a short note whenever a fresh lesson is published. No account needed and you can stop at any time.

Thank you. Your address has been noted in this browser session. Connect a mailing service to deliver the notes for real.