C#, lesson 10
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.
A class is a blueprint. Each object created from it has its own data and shares the class's methods.
What is going on:
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.new Counter("clicks") calls it
to set up a valid starting state.2 exercises to try what you just read.
public makes a member visible outside the class; members are private by default.static are instance methods: they run on one object and can use its
properties.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) { ... }.
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:
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.
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.
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 120Ada: 70 HP
Ada: 100 HP
Ada: 0 HP
Knocked out0 0
3 4
3 0Route: 9.00
Farthest: Point { X = 3, Y = 4 }