← Back to C# Course | Chapter 15: Modern C# Features | Lesson 1 of 6

Records (Immutable Data Types)

Records (Immutable Data Types)

C# 9 introduced record types for concise, immutable data models with built-in value-based equality, unlike classes which compare by reference. Because full record syntax needs a modern Roslyn compiler, this example instead builds the same idea manually with a class exposing readonly-style properties and a custom Equals — the pattern records exist to make less verbose. On a modern .NET SDK, the same model is a single line: record Point(int X, int Y);.

Note: On a full .NET SDK, prefer record Point(int X, int Y); — it generates the constructor, equality, and ToString automatically.

Example: Records (Immutable Data Types)

markup
using System;

class Point
{
    public int X { get; }
    public int Y { get; }

    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }

    public override bool Equals(object obj)
    {
        return obj is Point other && X == other.X && Y == other.Y;
    }

    public override string ToString() => $"Point({X}, {Y})";
}

class Program
{
    static void Main(string[] args)
    {
        Point p1 = new Point(1, 2);
        Point p2 = new Point(1, 2);

        Console.WriteLine(p1);
        Console.WriteLine(p1.Equals(p2));
    }
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.