Overview
With C# 9, developers will be able to write and manage code more efficiently with powerful features - records and enhanced pattern matching. The purpose of this article is to demonstrate how C# 9 records and pattern matching contribute to writing concise and readable code, by understanding their capabilities and demonstrating how they work together.
C# 9 Records: Simplicity in Data Structures
Immutable by Default
The compiler automatically generates an immutable class when you define a record in C# 9, which reduces boilerplate code.
In the code example below we have a Person record defined with two properties (FirstName and LastName). The compiler generates a class with these properties, making Person instances immutable.
using System.Collections;
namespace CSharp9RecordPatternMatchingExamples;
public class Data
{
//Immutable by Default example
public record Person(string FirstName, string LastName);
}
Value Equality
As a result, records implement value equality, comparing the values of their properties instead of references. This simplifies the code and makes it easier to read.
The code example below is in this case, the value equality check returns true since the property values are the same for both instances.
//Value Equality
var person1 = new Person("John", "Doe");
var person2 = new Person("John", "Doe");
if (person1 == person2)
{
Console.WriteLine("Both persons are equal.");
}
Deconstruction
In addition to supporting deconstruction, records allow easy extraction of property values.
As shown in the code example below, the FirstName and LastName properties are separated into separate variables.
//Deconstruction
var person = new Person("Jane", "Doe");
var (firstName, lastName) = person;
Console.WriteLine($"First Name: {firstName}, Last Name: {lastName}");
Pattern Matching: Enhancing Control Flow
Type Patterns
As a result of pattern matching, type checking, and casting are simplified, enhancing control flow constructs.
In the example code below, a switch statement is used to determine the type of object and display a corresponding message.
using System.Collections;
namespace CSharp9RecordPatternMatchingExamples;
public class Data
{
//Type Patterns
public static string GetDisplayText(object obj)
{
return obj switch
{
string text => $"String: {text}",
int number => $"Number: {number}",
DateTime dateTime => $"Date and Time: {dateTime}",
double floatingPoint => $"Floating Point Number: {floatingPoint}",
bool boolean => $"Boolean: {boolean}",
IEnumerable enumerable => $"Enumerable: {string.Join(", ", enumerable.Cast<object>())}",
_ => "Unknown"
};
}
}

Join the conversation! Your thoughts help the community grow.