C# 10.0 introduced record structs, expanding the concept of records to value types. This feature is useful for creating immutable value types with value-based equality semantics, similar to record classes but with the performance characteristics of structs.
Here’s how you can use record structs in your C# projects:
Declare Record Structs:
Use therecord struct
keyword to define a record as a value type. This is beneficial for smaller, immutable types where you want value-based equality.Benefit from Built-in Functionality:
Like record classes, record structs provide built-in functionality for value-based equality,ToString
,GetHashCode
, andEquals
methods.
Example:
public record struct Point(double X, double Y);
public static void Main()
{
var point1 = new Point(1.0, 2.0);
var point2 = new Point(1.0, 2.0);
Console.WriteLine(point1 == point2); // Output: True
Console.WriteLine(point1); // Output: Point { X = 1, Y = 2 }
}
In this example, Point
is a record struct that automatically supports value-based equality. Two instances of Point
with the same values are considered equal, and there's no need to manually override Equals
or GetHashCode
.
Record structs are particularly useful in scenarios where you need the immutability and equality behavior of records, but prefer the allocation efficiency of structs, such as in high-performance or memory-sensitive applications. They combine the best of both worlds from records and structs.
Top comments (0)