Records were introduced to make it easier to create simple data containers that hold values and compare them by their content, not by their location in memory.
0
0
Why records were introduced in C Sharp (C#)
Introduction
When you want to store data like a person's name and age without writing a lot of code.
When you need to compare two objects to see if they have the same data, not if they are the same object.
When you want your data objects to be easy to read and write with less chance of mistakes.
When you want to create immutable objects that cannot be changed after creation.
When you want built-in support for copying objects with some changes.
Syntax
C Sharp (C#)
public record Person(string Name, int Age);
This syntax creates a record with two properties: Name and Age.
Records automatically provide value-based equality and useful methods like ToString.
Examples
A simple record to hold X and Y coordinates.
C Sharp (C#)
public record Point(int X, int Y);
A record with properties that can only be set during creation (immutable).
C Sharp (C#)
public record Person { public string Name { get; init; } public int Age { get; init; } }
Shows that two records with the same data are equal.
C Sharp (C#)
var p1 = new Person("Alice", 30); var p2 = new Person("Alice", 30); Console.WriteLine(p1 == p2);
Sample Program
This program shows how records print their data and compare by content, not by reference.
C Sharp (C#)
public record Person(string Name, int Age); class Program { static void Main() { var person1 = new Person("John", 25); var person2 = new Person("John", 25); var person3 = new Person("Jane", 30); Console.WriteLine(person1); // Prints the data nicely Console.WriteLine(person1 == person2); // True because data is same Console.WriteLine(person1 == person3); // False because data differs } }
OutputSuccess
Important Notes
Records are great for data that should not change after creation.
They help avoid writing extra code for equality and string display.
Records use init properties to allow setting values only when creating the object.
Summary
Records simplify creating data containers with less code.
They compare objects by their data, not by memory location.
Records provide built-in support for immutability and easy copying.