Loading...

C# Records

Write a type that holds two values and compares by those values. In C# that is a record. One line declares it: public record Tag(string Name, int Count);. A Tag with pine and 20 prints its own values. Two Tag objects with the same values are equal. Two Hold objects with the same 12 are not.
The LINQ page printed five lines: pine, 12, pine x12, 12,8, pine x20. Those five stay first, from the same Hold, the same label, and the same Where. Optional Advanced continues, so nothing in that part changes. The 20 in pine x20 is the number the new record stores. Three lines go under the five. If dotnet run still stops at pine x20, the new lines are missing or dotnet run --no-build is running the LINQ program.

One line declares the record

Open PineLab. Keep using System; and using System.Linq;. Keep Hold<T> as it is. Under the closing brace of Hold<T>, outside every class, add:
public record Tag(string Name, int Count);
The part in parentheses is the primary constructor. From that one line the compiler writes a constructor that takes a string and an int, a property Name, a property Count, a ToString that prints both, and an equality check that compares both. The property names are PascalCase because they become public properties. You do not write a body. The semicolon ends the declaration.
In Main, under the five old WriteLine calls, build two tags and one more holder:
Tag tag = new Tag(word.Item, big.Sum());
Tag same = new Tag("pine", 20);
Hold<int> again = new Hold<int>(12);
Then print three things:
Console.WriteLine(tag);
Console.WriteLine(tag == same);
Console.WriteLine(number == again);

Hold, lambda, and Where, plus one record Tag

csharp
using System;
using System.Linq;

public class Hold<T>
{
    public T Item;

    public Hold(T item)
    {
        Item = item;
    }
}

public record Tag(string Name, int Count);

public class Pine
{
    public static void Main()
    {
        Hold<string> word = new Hold<string>("pine");
        Hold<int> number = new Hold<int>(12);
        Func<string, int, string> label = (name, count) => name + " x" + count;
        int[] counts = { 3, number.Item, 8 };
        int[] big = counts.Where(n => n > 5).ToArray();
        Console.WriteLine(word.Item);
        Console.WriteLine(number.Item);
        Console.WriteLine(label(word.Item, number.Item));
        Console.WriteLine(string.Join(",", big));
        Console.WriteLine(label(word.Item, big.Sum()));
        Tag tag = new Tag(word.Item, big.Sum());
        Tag same = new Tag("pine", 20);
        Hold<int> again = new Hold<int>(12);
        Console.WriteLine(tag);
        Console.WriteLine(tag == same);
        Console.WriteLine(number == again);
    }
}

Eight lines

Run dotnet run from PineLab. The first five lines are the LINQ screen: pine, 12, pine x12, 12,8, pine x20. Then three new lines:
Tag { Name = pine, Count = 20 }
True
False
The sixth line is the record printing itself. Console.WriteLine(tag) calls ToString, and the record's ToString writes the type name, then each property with its value, inside braces. You did not write that method. The one-line declaration made it.
The seventh line compares tag with same. tag was built from word.Item and big.Sum(). same was built from the literal "pine" and the literal 20. The values match, so == on two records gives True.
The eighth line compares number with again. Both hold 12. Hold<T> is a class, and == on two class objects asks whether they are the same object. They are two objects made by two new calls, so the answer is False.

Same values, two answers

Put the seventh and eighth lines side by side. Both pairs have matching values. One pair is equal and one is not. The difference is the kind of type, not the data.
A record compares by content. The compiler checks Name against Name and Count against Count. If every property matches, the records are equal. Build same as new Tag("pine", 21) and the seventh line turns into False. Change it back.
A class compares by identity unless someone writes their own equality. Hold<T> does not. Write Hold<int> again = number; instead, and the eighth line is True, because both names now point to one object. That is not the checked file. Put new Hold<int>(12) back.
The 20 inside the tag is the same sum as the fifth line. If you change the Where to n > 10, the fifth line becomes pine x12, the tag becomes Tag { Name = pine, Count = 12 }, and the seventh line becomes False, because same still holds 20. Put n > 5 back.

A record does not change after you build it

The properties from a positional record are init-only. You can set them while the object is being built, and not afterward. tag.Count = 21; fails the build. None of the eight lines appear. Delete that line.
When you want a tag with one value changed, C# makes a copy with with: Tag more = tag with { Count = 21 }; builds a new record with pine and 21 and leaves tag alone. The checked file does not use with. If a ninth line appears, you left an extra WriteLine in.
Hold<T> is different. Item is a public field, and number.Item = 13; compiles. The record keeps the two values fixed. The holder lets anyone overwrite its value. This page does not change either one.

Where the line goes

The record line sits outside Hold<T> and outside Pine, at the same level as the two classes. A file may hold two classes and a record. The entry point is still Pine.Main.
Do not put public record Tag(...) inside Main. A method body cannot declare a type, and the build fails. Inside the Pine class it would compile as a nested type, but then its full name changes, and this page keeps it beside Hold<T> so the three types read as one row of declarations.
The record also needs a C# version that knows the word record. Any current .NET SDK has one. The checked project already builds Func, generics, and LINQ, so it builds this line too.

Things this file leaves out

A record can have a body with methods, like a class: public record Tag(string Name, int Count) { ... }. This page uses the short form with a semicolon. A record struct is a value-type cousin. It is not in this file. A record class can inherit from another record. The inheritance page used classes, and this page does not add a base record.
Do not turn Hold<T> into a record. The eighth line exists to show a class next to a record. If Hold<T> became public record Hold<T>(T Item);, the eighth line would turn into True, number.Item would still read 12, and the comparison this page is built on would be gone.
Tag does not replace label. The fifth line still uses the lambda. The record stores the same two values the lambda joined.

xUnit comes next

You can keep the five LINQ lines and add a record that prints its own values and compares by them. The next page is xUnit. It writes tests that check results like pine x20 for you, so you do not have to read the screen. This page stops before that. There is no test project here and no [Fact].
One last pass: Hold<T> unchanged, public record Tag(string Name, int Count); under it, label and Where unchanged, tag from word.Item and big.Sum(), same from "pine" and 20, again from a second new Hold<int>(12). dotnet run shows the five old lines, then Tag { Name = pine, Count = 20 }, True, and False. When those eight lines match, the record did its job.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
5
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top