Skip to content

References, Values and Records

The Course
•
25 min study

This is the most important idea of the day, and it explains many confusing bugs. C# types come in two kinds, and assignment behaves differently for each.

  • Value types, such as int, double, bool and decimal. The variable holds the value itself, so assigning copies it.
  • Reference types, such as classes, lists and dictionaries. The variable holds a reference that says where the object is, and assigning copies the reference. You end up with two names for one object.

Two names, one object

Predict all four lines carefully before you run this. Draw a box for the object and arrows for the variables if it helps.

Copy a number, then copy a reference C#
int a = 10;
int b = a;
b = 20;
Console.WriteLine(a);

var first = new Counter();
var second = first;
second.Count = 20;
Console.WriteLine(first.Count);

var third = new Counter();
third.Count = 20;
Console.WriteLine(first == second);
Console.WriteLine(first == third);

class Counter
{
    public int Count { get; set; }
}
Check your prediction
Text
10
20
True
False

For classes, == asks "are these the same object?" rather than "do they contain the same data?". third holds the same number as first, but it's a different object.

Methods can change what they receive

A parameter is always a copy, as you saw on Day 3. With a reference type, though, it's a copy of the reference, so the method can reach the caller's object. That explains why a method can add to your list but can't replace your list.

Change the list, or change the variable? C#
var minutes = new List<int> { 25 };

AddSession(minutes);
Console.WriteLine(minutes.Count);

ReplaceList(minutes);
Console.WriteLine(minutes.Count);

static void AddSession(List<int> values)
{
    values.Add(10);
}

static void ReplaceList(List<int> values)
{
    values = new List<int>();
    values.Add(1);
}
Check your prediction
Text
2
2

ReplaceList pointed its own copy of the reference at a new list. The caller's minutes never noticed. If you want a separate list you can change safely, create one with new List<int>(minutes).

Records: data that compares by value

A record is a type for simple data, and one line declares it. The compiler generates a constructor, read-only properties, readable printing, and == that compares contents rather than identity. You can't change the properties of a record declared this way; with makes a copy with some values replaced.

A record in one line C#
var task = new StudyTask("Read", 25, false);
var same = new StudyTask("Read", 25, false);
var finished = task with { Done = true };

Console.WriteLine(task);
Console.WriteLine(finished);
Console.WriteLine(task == same);
Console.WriteLine(task == finished);

record StudyTask(string Title, int Minutes, bool Done);
Check your prediction
Text
StudyTask { Title = Read, Minutes = 25, Done = False }
StudyTask { Title = Read, Minutes = 25, Done = True }
True
False

Because task can't change, you can pass it to any method without wondering what will happen to it. This comes from the one-line form. A record can also declare settable properties, and if a property holds a list, the list's contents can still change even though the property can't point to another list. To update a record held in a list, replace the entry. Assigning to the item directly, as in tasks[0].Done = true;, is a compile error.

Replace an item in a list C#
var tasks = new List<StudyTask> { new StudyTask("Read", 25, false) };

tasks[0] = tasks[0] with { Done = true };
Console.WriteLine(tasks[0].Done);

record StudyTask(string Title, int Minutes, bool Done);
Check your prediction
Text
True

As a rule of thumb, use a record for a simple piece of data that you'd compare by its contents, and a class when something has an identity and rules about how it changes. A planner is a class; a task inside it can be a record.

Your turn

Exercise

Finish without changing the original

Declare a record Goal(string Name, int Target, int Done). Write a static method Advance(Goal goal, int amount) that returns a new Goal with Done increased by amount, but never above Target. Start with Reading, a target of 100 and 90 done. Advance by 25, then print the original's Done and the new one's Done.

Your workspace C#
Console.WriteLine("Put your record under this line");
Hint 1: the idea

This record can't be changed, so the method builds a new one and returns it. The original stays exactly as it was.

Hint 2: a first step

Declare the record at the bottom of the file, create one, and print it to see what the generated output looks like.

Show one solution
C#
var original = new Goal("Reading", 100, 90);
var advanced = Advance(original, 25);

Console.WriteLine(original.Done);
Console.WriteLine(advanced.Done);

static Goal Advance(Goal goal, int amount)
{
    return goal with { Done = Math.Min(goal.Target, goal.Done + amount) };
}

record Goal(string Name, int Target, int Done);
Text
90
100

with makes a new record with one value changed and leaves original untouched, which is why the first line still prints 90. Math.Min caps the progress at the target, so advancing by 25 gives 100 rather than 115.

Explain, without running it, what would differ if Goal were a class with settable properties and Advance changed goal.Done directly. Then look back at the first example of this lesson to check your reasoning.

Was this article helpful?

Your response is saved on this device.