Learn/C#/10. Classes and records
Lesson 10 of 15
Sign in

C#, lesson 10

Classes and records

Loose variables get messy fast: a name here, a score there, a list of both somewhere else. C# lets you define your own types that bundle related data and the code that works on it.

Classes: state and behaviour

A class is a blueprint. Each object created from it has its own data and shares the class's methods.

What is going on:

  • Properties such as Count { get; private set; } look like fields from outside but control access. Here other code can read Count but only the class itself can change it. That is encapsulation: the class protects its own rules (a counter never goes backwards, a health bar never exceeds 100) because nothing else can modify its data directly.
  • The constructor has the class's name and no return type. new Counter("clicks") calls it to set up a valid starting state.

2 exercises to try what you just read.

Exercise 1

Game character

Press Ctrl Enter or Check to test your code.

Exercise 2

Delivery route

Press Ctrl Enter or Check to test your code.

  • public makes a member visible outside the class; members are private by default.
  • Methods without static are instance methods: they run on one object and can use its properties.
  • Overriding ToString decides how the object prints.
  • With top-level statements, your classes go below the statements in the same file.

    C# 12 added primary constructors, a shorter way to take constructor parameters that the whole class can use: class Counter(string label) { ... }.

    Records: data with value equality

    Many types are just a bundle of values: a point, a price, a date range. A record gives you a constructor, read-only properties, value-based equality, a readable ToString and deconstruction from a single line:

    Two ordinary class objects are equal only if they are the same object. Two records are equal when all their values match, which is usually what you want for data. Records are immutable by default, so instead of changing one you create a modified copy with a with expression.

    You can add methods to a record in a body:

    Structs in one paragraph

    A struct is a value type: assigning it copies the whole value, while assigning a class object copies only a reference to the same object. Built-in types such as int, double and DateTime are structs. Use record struct for tiny values like coordinates when you care about avoiding allocations; otherwise records and classes are the everyday choice.

    Class or record?

    Use a record for values defined by their data that do not change: coordinates, money amounts, results. Use a class for things with an identity whose state changes over time: a bank account, a game character, a shopping cart.

    Further reading

    • Classes
    • Record types
    • Properties
    • Primary constructors

    Complete the Hero class. A hero has a Name and Hp (health points) that start at 100.

    • TakeHit(int damage) lowers Hp, but never below 0.
    • Heal(int amount) raises Hp, but never above 100.
    • IsAlive is a property that is true while Hp is above 0.
    • ToString() returns <name>: <hp> HP.

    The first input line is the hero's name. Each following line is hit <n> or heal <n>. After every command the program prints the hero, and at the end it prints Still standing or Knocked out. The top-level code is already written for you.

    Sample input:

    Sample output:

    Declare a record Point(double X, double Y) with a method double DistanceTo(Point other) that returns the straight-line distance, Math.Sqrt(dx * dx + dy * dy).

    The input has one stop per line, as x y. A delivery van visits the stops in order. Print the total length of the route with two decimals, then the stop farthest from the origin (0, 0) printed with the record's own ToString. If two stops are equally far, keep the first. There is always at least one stop.

    Sample input:

    Sample output:

    var clicks = new Counter("clicks");
    clicks.Increment();
    clicks.Increment();
    Console.WriteLine(clicks.Count);   // 2
    Console.WriteLine(clicks);         // clicks=2
    
    class Counter
    {
        public string Label { get; }          // read-only property
        public int Count { get; private set; } // anyone can read, only Counter can change
    
        public Counter(string label)          // constructor
        {
            Label = label;
        }
    
        public void Increment() => Count++;
    
        public override string ToString() => $"{Label}={Count}";
    }
    var p = new Point(3, 4);
    Console.WriteLine(p.X);                        // 3
    Console.WriteLine(p);                          // Point { X = 3, Y = 4 }
    Console.WriteLine(p == new Point(3, 4));       // True: same values
    var moved = p with { X = 10 };                 // copy with one change
    Console.WriteLine(moved);                      // Point { X = 10, Y = 4 }
    
    record Point(int X, int Y);
    record Temperature(double Celsius)
    {
        public double Fahrenheit => Celsius * 9 / 5 + 32;
    }
    Ada
    hit 30
    heal 50
    hit 120
    Ada: 70 HP
    Ada: 100 HP
    Ada: 0 HP
    Knocked out
    0 0
    3 4
    3 0
    Route: 9.00
    Farthest: Point { X = 3, Y = 4 }