🚀 C# ile Programlamaya Giriş: Kodlamaya İlk Adımını At, Kendi Projelerini Geliştirmeye Başla!
00HOME
07GLOSSARY 08TAGS ♡MY LIST ⌕SEARCH
TRENG

Records and Pattern Matching

You learn record types that define measurement data in a single line, copying with with, and making decisions in a switch expression with property, type and logical patterns.

Most of the data moving around a measurement system comes in "small packages": channel name, value, unit, time. These packages have little behaviour, but they must be carried, compared and printed correctly. Writing a class for them means a lot of repetition: constructor, properties, ToString. C#'s record type reduces all of that to a single line. Pattern matching turns making decisions about these packages from piles of nested ifs into a readable table. You saw the line record Reading(...) in the LINQ lesson; now we look at what is behind it.

record: a short class for data

Every parameter you write in the parentheses automatically becomes a read-only (init-only) property. The compiler generates the constructor, value equality, a readable ToString and deconstruction for you.

var a = new Reading("CH1", 3.3, "V");
var b = new Reading("CH1", 3.3, "V");

Console.WriteLine(a);
Console.WriteLine(a == b);                 // same content?
Console.WriteLine(ReferenceEquals(a, b));  // same object?

var (channel, value, unit) = a;            // take it apart
Console.WriteLine($"{value} {unit} on channel {channel}");

record Reading(string Channel, double Value, string Unit);
Reading { Channel = CH1, Value = 3.3, Unit = V }
True
False
3.3 V on channel CH1

a and b are two separate objects in memory (ReferenceEquals is false), but because their contents are the same, == gives true. If you made the same definition with an ordinary class, == would return false and Console.WriteLine(a) would print only the class name. Records are reference types like classes; if you want a value type, you can write record struct.

with: copying with changes

A record's properties cannot be changed after it is created. This is not a limitation but a guarantee: a measurement record does not change secretly in some corner of the program. When you want a changed version, you make a copy with with. For example, let us correct a sensor offset of 0.25 V:

var raw = new Reading("CH2", 4.75, "V");
var calibrated = raw with { Value = raw.Value - 0.25 };

Console.WriteLine(raw);
Console.WriteLine(calibrated);

record Reading(string Channel, double Value, string Unit);
Reading { Channel = CH2, Value = 4.75, Unit = V }
Reading { Channel = CH2, Value = 4.5, Unit = V }

The raw data stays as it was; the calibrated value is in a new record. In measurement software, keeping the raw data lets you undo a faulty calibration later.

Property patterns in a switch expression

In the conditions lesson you used the switch expression with numbers. Patterns can do much more: a property pattern such as { Unit: "V", Value: < 0 } looks at several properties of an object at once. You can combine patterns with and, or and not.

var readings = new[]
{
    new Reading("CH1", 3.3, "V"),
    new Reading("CH2", 4.1, "V"),
    new Reading("CH3", -0.2, "V"),
    new Reading("T1", 85, "C"),
    new Reading("P1", 1.2, "bar")
};

foreach (var r in readings)
    Console.WriteLine($"{r.Channel}: {Evaluate(r)}");

static string Evaluate(Reading r) => r switch
{
    { Unit: "V", Value: < 0 }               => "Reverse voltage",
    { Unit: "V", Value: >= 3.0 and <= 3.6 } => "Normal",
    { Unit: "V" }                          => "Out of tolerance",
    { Unit: "C", Value: >= 80 }             => "Overheated",
    { Unit: "C" }                          => "Normal",
    _                                      => "Unknown unit"
};

record Reading(string Channel, double Value, string Unit);
CH1: Normal
CH2: Out of tolerance
CH3: Reverse voltage
T1: Overheated
P1: Unknown unit

You can read it like a table of rules. Arms are tried from top to bottom, which is why the narrow conditions (Value: < 0) stand in front of the general ones ({ Unit: "V" }). You can use the same patterns in an if as well: if (r is { Unit: "C", Value: >= 80 }).

Type patterns and record inheritance

Records can derive from each other. A signal can be analog or digital; the switch expression decides by looking at both the type and the content. The syntax Digital(true) is a positional pattern: it takes the record apart and checks whether the first part is true.

Signal[] signals = { new Analog(1.2), new Analog(4.7), new Digital(true), new Digital(false) };

foreach (Signal s in signals)
{
    string description = s switch
    {
        Analog { Volts: > 2.5 } a => $"Analog high ({a.Volts} V)",
        Analog a                  => $"Analog low ({a.Volts} V)",
        Digital(true)             => "Digital: ON",
        Digital(false)            => "Digital: OFF",
        _                         => "Unknown signal"
    };
    Console.WriteLine(description);
}

abstract record Signal;
record Analog(double Volts) : Signal;
record Digital(bool State) : Signal;
Analog low (1.2 V)
Analog high (4.7 V)
Digital: ON
Digital: OFF

The arm Analog { Volts: > 2.5 } a does three jobs at once: it checks that the type is Analog, looks at whether the voltage is above 2.5 V, and makes the matching object available under the name a. It is a much more powerful form of the is type check from the inheritance lesson.

Common mistakes

  • Writing the general arm first: If the arm { Unit: "V" } comes before { Unit: "V", Value: < 0 }, the second one never gets its turn. The compiler reports this as an error ("already handled").
  • Forgetting the _ arm: The compiler warns you; if a value that matches no arm arrives, the program throws a SwitchExpressionException at run time.
  • Keeping a list in a record and expecting equality: When comparing two records of record Log(List<double> Values), C# does not look inside the lists but checks whether they are the same list object. with does not copy the list either; both records share the same list.

Exercise

Define record MotorState(double Current, double Temperature, bool Running). A Diagnose method applies these rules with a switch expression: if the motor is not running, "Stopped"; if the temperature is above 90 degrees, "Overheating, stop it"; if the current is above 12 A or the temperature is above 75 degrees, "Warning"; otherwise "Normal". Start with a running motor at 8 A and 60 degrees; then, using with, raise the current to 13.5 A, the temperature to 95 degrees, and finally stop the motor. Print the record and the diagnosis at each step.

Hint: You can combine two property patterns with or: { Current: > 12 } or { Temperature: > 75 }. The order of the arms sets the priority of the diagnosis; put the most critical case at the top.

Solution

var m1 = new MotorState(8, 60, true);
var m2 = m1 with { Current = 13.5 };
var m3 = m2 with { Temperature = 95 };
var m4 = m3 with { Running = false };

foreach (var m in new[] { m1, m2, m3, m4 })
    Console.WriteLine($"{m} -> {Diagnose(m)}");

static string Diagnose(MotorState m) => m switch
{
    { Running: false }                        => "Stopped",
    { Temperature: > 90 }                     => "Overheating, stop it",
    { Current: > 12 } or { Temperature: > 75 } => "Warning",
    _                                         => "Normal"
};

record MotorState(double Current, double Temperature, bool Running);
MotorState { Current = 8, Temperature = 60, Running = True } -> Normal
MotorState { Current = 13.5, Temperature = 60, Running = True } -> Warning
MotorState { Current = 13.5, Temperature = 95, Running = True } -> Overheating, stop it
MotorState { Current = 13.5, Temperature = 95, Running = False } -> Stopped

Four different states, a four-line rule table and not a single nested if. Because the old record is kept at every step, you could easily store the motor's history in a list if you wanted.

You have learned to carry data safely and to make decisions by looking at it. In the next lesson we will write these records to a CSV file and read them back.

// Spot the bug +10 XP

Exactly one line below is wrong. Click the faulty line.

// Mini quiz

Click an option; you will see right away, with the reason, whether it is correct or not.

1. Given record Reading(string Channel, double Value);, what is the result of new Reading("CH1", 3.3) == new Reading("CH1", 3.3)?
2. What does the line var k = r with { Value = 3.5 }; do?
3. In a switch expression, what happens if the { Value: > 0 } arm is written first and the { Value: > 100 } arm after it?

Mark it when you finish: your progress is saved and you earn +20 XP.

Tip: ← → keys let you move between lessons.