WeCodeAcademy

C# Tuples, Records and Pattern Matching

ExampleC#
using System;

record Person(string Name, int Age);

class Program
{
    static (int Min, int Max) MinMax(int[] values)
    {
        int min = values[0], max = values[0];
        foreach (int v in values)
        {
            if (v < min) min = v;
            if (v > max) max = v;
        }
        return (min, max);
    }

    static string Describe(object o) => o switch
    {
        int n when n > 100 => "big number",
        int n => "number " + n,
        string s => "text of length " + s.Length,
        null => "nothing",
        _ => "something else"
    };

    static void Main()
    {
        var (lo, hi) = MinMax(new[] { 5, 2, 9, 1 });
        Console.WriteLine(lo + " " + hi);

        Person a = new Person("Ada", 36);
        Person b = a with { Age = 37 };
        Console.WriteLine(a);
        Console.WriteLine(b);
        Console.WriteLine(a == new Person("Ada", 36));

        Console.WriteLine(Describe(7));
        Console.WriteLine(Describe(500));
        Console.WriteLine(Describe("hello"));
        Console.WriteLine(Describe(null));
    }
}
Output
1 9
Person { Name = Ada, Age = 36 }
Person { Name = Ada, Age = 37 }
True
number 7
big number
text of length 5
nothing

A record is a short way to declare an immutable data class with value-based equality: the last comparison is True because the names and ages match.

Quick check

What does a record give you automatically?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.