Records (Immutable Data Types)
A record is a compact type for holding information that does not change, like a printed name tag. Two records with the same details count as equal.
In this page:
Syntax
record RecordName(type Property1, type Property2); // C# 9 immutable data type
var copy = original with { Property1 = newValue };
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Expecting a
recordto be mutable, when its properties are init-only by default. - Using a
recordwhen you need reference identity. - Forgetting the
withexpression for creating a modified copy.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: