Home
Blog
When to Use Records in C#
Updated
Dot Net Perls

When to Use Records in C#

Often when developing C# programs we have small classes that only have a couple fields or properties. For example, a Point may have just two fields—its coordinates. Do these types need an entire class, with a constructor? Or should we condense the logic and keep the program smaller?

With records, we can specify—in a single line—a class that has some fields. Each field has a type and a name. There are some limitations with records, however, so it is best to use them only when certain conditions are true. We can use records when a class:

Has no methods, properties, or custom constructors.
Has no complex inheritance issues (a derived class) and does not implement any interfaces.
Is unlikely to need any of the previously-mentioned features in the future.

Records, which are also available in Java, can define a class with different fields in a single line. They remind me of tuple classes in Rust as well. If I were developing a program in C# or Java, I would aspire to use records when adding types—this would help keep the code base smaller and easier to manage.

Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
An RSS feed is available for this blog.
Home
Changes
© 2007-2025 Sam Allen