record ExamplesInstantiate records and use them in programs. Use the built-in formatting method on a record.
This page was last reviewed on Dec 16, 2022.
Record. 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.
Some more features. Records can be compared by value—all the contents are tested automatically, with no extra logic needed. This simplifies C# programs.
Example program. 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.
Detail To create a record, we can use the new keyword directly. A type is needed (we cannot use var instead of Box in this example).
Detail When 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.
Note Try changing one of the Test record instances to have a different value, and the word "EQUAL" will not be printed.
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"); } } }
Copy with. 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 }
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 16, 2022 (new example).
© 2007-2023 Sam Allen.