In C#, a record is a special type of class introduced in C# 9.0 that is designed to model immutable data. Unlike regular classes, records are intended to be more concise and automatically provide value-based equality, meaning that two record instances with the same data are considered equal.
Here are some key features of record:
Concise Syntax: Records use a more concise syntax to define data models.
Immutability: Properties in records are immutable by default.
Value-Based Equality: Records automatically provide value-based equality and comparison, unlike classes that use reference-based equality.
Deconstruction: Records support deconstruction to easily extract property values.
Here's a basic example of a record in C#:
csharp
public record Person
{
public int ID { get; init; }
public string FirstName { get; init; }
public string LastName { get; init; }
public string Address { get; init; }
}
//==============================
public record Person(string FirstName, string LastName);
//==============================
This defines a Person record with two properties, FirstName and LastName. You can create and use records like this:
csharp
public record Person(string FirstName, string LastName);
var person1 = new Person("John", "Doe");
var person2 = new Person("John", "Doe");
Console.WriteLine(person1 == person2); // Outputs: True (value-based equality)
Console.WriteLine(person1.FirstName); // Outputs: John
// Deconstruction
var (firstName, lastName) = person1;
Console.WriteLine(firstName); // Outputs: John
Console.WriteLine(lastName); // Outputs: Doe