c# · level 2 · unit 4 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A is a data class written in one line.
Lots of classes only carry data: a book's title and price, a point on a map. A record writes all of that in one line. record Book(string Title, decimal Price); builds the constructor, a property for each part, and a ToString that shows them all.
Records use : two records with the same contents are equal, so == gives True. Two class objects are only equal when they are the very same object, even if every field matches.
A record's properties are set once, when it is built. That makes it , so a.Price = 5; is refused with CS8852.
using System;
var a = new Book("Holes", 6.99m);
var b = new Book("Holes", 6.99m);
Console.WriteLine(a);
Console.WriteLine(a == b);
Console.WriteLine($"{a.Title} costs {a.Price}");
record Book(string Title, decimal Price); Record parts are properties, so they start with a capital letter.
guess first
A record and a class walk in. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
var p1 = new Point(2, 3);
var p2 = new Point(2, 3);
var s1 = new Spot();
var s2 = new Spot();
Console.WriteLine($"{p1 == p2} {s1 == s2}");
record Point(int X, int Y);
class Spot { }
your turn
Your turn. Make a film record.
On line 7, turn Film into a record. Then put a film and the year it came out on line 3, and press run.
output
press run to see what happens
fix it
The order cannot be changed. Fix it!
output
press run to see what happens
- C# says
CS8852on line 4:Quantitycan only be set when the record is built. - A record is immutable, so build it with the right quantity from the start.
- Change line 3 to
var order = new Order("pizza", 3);and delete line 4, then press run.
nailed it
your data fits on one line. :D
- A record builds a constructor, properties and
ToString. - Records with the same contents are equal.
- Records are immutable once built.
new words in your collection
- record
- value equality
- immutable
This lesson isn’t saved. A free account remembers every lesson you finish.