C# 9 Features: Records and Pattern Matching
Introduction
C# 9 introduces powerful new features that enhance the language's expressiveness and readability. This guide explores two key features: records and pattern matching. Records simplify data classes, while pattern matching streamlines conditional logic. Sample code is included to illustrate how to leverage these features effectively.
Records in C# 9
Records are a new reference type in C# that provide concise syntax for defining classes intended to store data. Key points include:
- Immutable by Default: Records are immutable by default, meaning their values cannot change after creation.
- Value Equality: Records define value equality, so two records with the same values are considered equal, simplifying comparisons.
- Concise Declaration: Records can be declared with minimal code, as the compiler generates common methods like
Equals
,GetHashCode
, andToString
.
Pattern Matching in C# 9
Pattern matching in C# 9 enhances the language's ability to handle conditional logic. Key points include:
- Enhanced
switch
: Theswitch
statement now supports patterns, allowing you to match patterns in a more expressive way. - Pattern Variations: Patterns support variations like type patterns, property patterns, and positional patterns, making it versatile for different use cases.
- Deconstruction: Pattern matching supports deconstruction, enabling you to extract values from objects in a structured manner.
Sample Code
Below are sample C# code snippets that demonstrate the use of records and pattern matching.
C# Code (Records Example):
public record Person(string FirstName, string LastName);
var person1 = new Person("John", "Doe");
var person2 = new Person("John", "Doe");
Console.WriteLine(person1 == person2); // Value equality
C# Code (Pattern Matching Example):
public class Shape
{
public int Sides { get; set; }
}
public class Circle : Shape
{
public int Radius { get; set; }
}
Shape shape = new Circle { Sides = 1, Radius = 5 };
string description = shape switch
{
Circle { Radius: 5 } => "A small circle",
Circle { Radius: 10 } => "A large circle",
_ => "Unknown shape"
};
Console.WriteLine(description);
Conclusion
C# 9 introduces records and pattern matching, two powerful features that simplify data handling and streamline conditional logic. Records provide concise syntax for defining data classes, and pattern matching enhances the readability of conditional statements. By incorporating these features into your C# code, you can create more expressive and efficient applications.