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,boolanddecimal. 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.
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
10
20
True
FalseFor 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.
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
2
2ReplaceList 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.
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
StudyTask { Title = Read, Minutes = 25, Done = False }
StudyTask { Title = Read, Minutes = 25, Done = True }
True
FalseBecause 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.
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
TrueAs 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
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.
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
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);90
100with 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.
Completion is saved in this browser only. It does not measure mastery.