Records (Immutable Data Types)
In this page:
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)
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));
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: