C# Exception Handling
C# File I/O
C# Delegates and Events
C# Generics
C# Async Programming
C# Records

C# Records

Records (C# 9+) are immutable reference types with built-in value equality, deconstruction, and a concise syntax.

1 - Positional Record

public record Point(double X, double Y);

var p1 = new Point(1, 2);
var p2 = new Point(1, 2);
var p3 = new Point(3, 4);

Console.WriteLine(p1 == p2); // True  — value equality!
Console.WriteLine(p1 == p3); // False

Console.WriteLine(p1);       // Point { X = 1, Y = 2 }

2 - with Expression (Non-Destructive Mutation)

var alice  = new Point(1, 2);
var moved  = alice with { X = 10 }; // creates a new record

Console.WriteLine(alice); // Point { X = 1, Y = 2 }
Console.WriteLine(moved); // Point { X = 10, Y = 2 }

3 - Record with Methods

public record Person(string Name, int Age)
{
    public bool IsAdult => Age >= 18;
    public string Greet() => $"Hi, I'm {Name}!";
}

var person = new Person("Alice", 30);
Console.WriteLine(person.IsAdult);  // True
Console.WriteLine(person.Greet());  // Hi, I'm Alice!

4 - Record Struct (C# 10)

// Value semantics + record features
public record struct Coordinate(double Lat, double Lng);

var loc = new Coordinate(48.8566, 2.3522);
Console.WriteLine(loc); // Coordinate { Lat = 48.8566, Lng = 2.3522 }

Note: Use records for DTOs, value objects, and domain models that should not change after creation. The with expression lets you derive modified copies without mutation — a key functional programming pattern.

-Tip-