Junior — Middle
What is the difference between the Record data type and Struct in programming?
sobes.tech AI
Answer from AI
In C# record and struct are different data types with different purposes and behaviors.
-
Record is a reference type, designed for creating immutable objects with value semantics. Records automatically implement
Equals(),GetHashCode(), andToString()methods based on property values, which is convenient for comparison and copying objects. -
Struct is a value type, stored on the stack and copied by value. Structs are typically used for small, lightweight objects where performance and minimizing heap allocations are important.
Main differences:
| Characteristic | Record (class) | Struct |
|---|---|---|
| Type | Reference type | Value type |
| Mutability | Usually immutable | Can be mutable |
| Storage | On the heap | On the stack or inline |
| Comparison | By value (property values) | By value (all fields) |
| Usage | For complex objects with logic | For lightweight data |
Example of a record:
public record Person(string FirstName, string LastName);
var p1 = new Person("Ivan", "Ivanov");
var p2 = new Person("Ivan", "Ivanov");
Console.WriteLine(p1 == p2); // True, comparison by values
Example of a struct:
public struct Point
{
public int X { get; set; }
public int Y { get; set; }
}
var point1 = new Point { X = 1, Y = 2 };
var point2 = point1; // copy by value
point2.X = 3;
Console.WriteLine(point1.X); // 1