Records, Structs and Enums
Records: Data with Value Equality
A record is a class designed to hold data. The compiler creates equality, ToString() and copying for you.
csharp
record Person(string Name, int Age);
var a = new Person("Ana", 25);
var b = new Person("Ana", 25);
Console.WriteLine(a == b); // True : compared by VALUES
Console.WriteLine(a); // Person { Name = Ana, Age = 25 }
var older = a with { Age = 26 }; // copy with one change (a is not modified)
Console.WriteLine(older);
| class | record | |
|---|---|---|
| Equality | By reference (same object) | By values (same data) |
| Mutability | Usually changeable | Immutable by default with positional syntax |
| Best for | Objects with behavior | DTOs, messages, simple data |
Deconstruction
csharp
var (name, age) = a;
Console.WriteLine($"{name} is {age}");
Structs: Small Value Types
csharp
struct Point
{
public int X;
public int Y;
}
Point p1 = new() { X = 1, Y = 2 };
Point p2 = p1; // COPY of the values
p2.X = 99;
Console.WriteLine(p1.X); // 1 : p1 unchanged
| class | struct | |
|---|---|---|
| Type | Reference | Value |
| Copy | Copies the reference | Copies the data |
| Memory | Heap | Usually stack or inside the owner |
| Use for | Most things | Tiny, immutable values (point, color, coordinate) |
Start with class: Use a
struct only for small, immutable values (about 16 bytes or less). A readonly record struct is a good modern choice.
csharp
readonly record struct Money(decimal Amount, string Currency);
Enums: Named Choices
csharp
enum OrderStatus
{
Pending, // 0
Paid, // 1
Shipped, // 2
Delivered // 3
}
OrderStatus status = OrderStatus.Paid;
string message = status switch
{
OrderStatus.Pending => "Waiting for payment",
OrderStatus.Paid => "Preparing",
OrderStatus.Shipped => "On the way",
OrderStatus.Delivered => "Done",
_ => "Unknown"
};
Console.WriteLine((int)status); // 1
var parsed = Enum.Parse<OrderStatus>("Shipped");
Flags Enums
csharp
[Flags]
enum Permission
{
None = 0,
Read = 1,
Write = 2,
Delete = 4
}
Permission p = Permission.Read | Permission.Write;
Console.WriteLine(p.HasFlag(Permission.Write)); // True
Console.WriteLine(p); // Read, Write
Conclusion
Use records for data, structs for tiny value types, classes for everything with behavior and enums for fixed sets of choices.
Quick Summary: record = data with value equality, struct = value type, enum = named constants.

