How to Use Record Structs in C#
Introduction to Record Structs in C#
Record structs, introduced in C# 9.0, are a type of value type that combines features of structs and records. They are designed to provide an efficient way to represent simple data aggregates with value-based equality semantics.
Key Features and Usage
-
Immutable by Default:
- Record structs are immutable, meaning their state cannot be altered after they are created.
- This immutability is enforced by the
init
accessor in property declarations, which allows property values to be set only during object initialization.
-
Value-Based Equality:
- Record structs automatically implement
IEquatable<T>
, enabling value-based equality checks instead of reference-based (default for objects). - This feature is particularly useful for structs as they are often used to represent simple data types where value equality is more relevant than reference identity.
- Record structs automatically implement
-
Built-In Support for Interfaces:
- Implementations for
IStructuralEquatable
andIStructuralComparable
are provided out of the box. - These interfaces support advanced comparison and sorting operations based on the values of the struct’s properties.
- Implementations for
-
Nondestructive Mutation with the
with
Expression:- The
with
keyword creates a new record struct instance by copying existing values and allowing modifications. - This is useful for creating variations of immutable structures without altering the original instance.
- The
Code Example with with
Expression
record struct Point { public int X { get; init; } public int Y { get; init; } } var point = new Point { X = 1, Y = 2 }; var newPoint = point with { X = 3 }; // X is now 3, Y remains 2
Additional Considerations
-
Deconstructor Support:
- Record structs can include a deconstructor, allowing properties to be easily decomposed into variables.
-
Record Structs vs Record Classes:
- Unlike record classes (which are reference types), record structs are value types and are stored on the stack, leading to potential performance benefits in certain scenarios.
-
Suitable Use Cases:
- They are ideal for small, immutable data structures, especially where value equality and efficient copying are important, such as in functional programming paradigms.
-
Limitations:
- Being value types, record structs can lead to increased memory usage if used improperly, especially with large data sets.
Conclusion
Record structs in C# provide a robust and efficient way to handle simple data structures with value-based equality and immutability. They streamline certain programming tasks, particularly where data integrity and consistent behavior are paramount. Understanding when and how to use them effectively can be a valuable addition to a C# developer’s toolkit.
If you want to skyrocket your C# career, check out our powerful ASP.NET FULL-STACK WEB DEVELOPMENT COURSE, which also covers test-driven development and C# software architecture.