In C# a record is a simple reference type like a class
, but with more built-in features. For example it can print out its contents with no extra code.
Records can be compared by value—all the contents are tested automatically, with no extra logic needed. This simplifies C# programs.
Here we create a record class
with the name Box. It has 2 fields—a string
that indicates its color, and an int
that indicates its size.
var
instead of Box in this example).Console.WriteLine
is called, the Box record's built-in output code is used to print out its internal contents.using System; class Program { record Box(string Color, int Dimension); static void Main() { // Create new instance of the Box record. Box box = new("blue", 10); // A formatting method is built-in. Console.WriteLine(box); } }Box { Color = blue, Dimension = 10 }
Equals
Two record instances can be tested for equality. This compares all of the internal fields of both records—strings, ints, and other types are supported.
using System; class Program { record Test(int one, int two); static void Main() { var test1 = new Test(1, 2); var test2 = new Test(1, 2); if (test1 == test2) { Console.WriteLine("EQUAL"); } } }EQUAL
It is possible to copy a record instance and change certain fields in the copy. This requires a single statement—the "with" keyword is required.
using System; class Program { record Bird(string Color, int Feathers); static void Main() { Bird bird1 = new("blue", 1000); // Copy the bird and change its color to yellow. Bird bird2 = bird1 with { Color = "yellow" }; // Print the birds. Console.WriteLine(bird1); Console.WriteLine(bird2); } }Bird { Color = blue, Feathers = 1000 } Bird { Color = yellow, Feathers = 1000 }
Records can be classes or structs, but a "record" with no additional specification is a class
. It includes built-in functionality that simplifies C# programs.