Exploring C# 9's Record Types

Introduction

C# 9 brings in a new feature called record types that make building immutable data structures easier. Whether you are just starting with C# or have been coding for a while, knowing about record types can really level up your coding. In this simple blog post we will go over the basics of C# 9's record types, checking out how they work, why they're great, and some examples to help you understand better.

Understanding Records in C# 9

Records offer a straightforward way to define immutable data structures. Unlike regular classes, records come with built-in features like value-based equality, immutability, and deconstruction, which makes them perfect for handling data entities in your programs.

Syntax

Let's take a look at how record types are structured. In C# 9, creating a record is straightforward: you use the record keyword followed by the record's name and its properties enclosed in parentheses. Here is a simple example:

public record Person
{
    public string FirstName { get; init; }
    public string LastName { get; init; }
}

In this example, we have created a Person record with two properties: FirstName and LastName. By using the init accessor, we ensure that these properties can only be set during object initialization, which helps maintain immutability.

Benefits of Record Types

  1. Concise Syntax: Record types allow you to create complex data structures with just a few lines, reducing unnecessary code and making your program easier to manage.
  2. Value-based Equality: With record types, you get automatic value-based equality, so you can compare two records based on their property values rather than references.
  3. Immutable Properties: Record properties are immutable by default, which means they can not be changed after object initialization. This feature helps prevent unintended side effects and improves code predictability.

Examples

1. Creating Records

var person1 = new Person { FirstName = "Lalji", LastName = "Dhameliya" };
var person2 = new Person { FirstName = "Lalji", LastName = "Dhameliya" };

2. Value-based Equality

bool areEqual = person1.Equals(person2); // true if FirstName and LastName are equal

3. Deconstruction

var (first, last) = person1; // Deconstructing a record into individual variables

Conclusion

C# 9's record types make it easy to organize data and write better code. They're simple to use, offer fair comparison methods, and keep your data safe from unwanted changes. Whether you're dealing with basic or complicated data, record types are a smart choice. Try them out in your C# projects today and see how they can make your coding life easier!

Next Recommended Reading Data Types & Type Conversions in C#