How to Use Records in C# — Part 1
With C# 9, we had record types introduced to the language, later the record types had some changes in C# 10 which I will explain later in another article.
What’s the Record Type
Record is a class with default implementations for some of the functionalities to make developers day to day life easier. These are mainly everything related to equality like Equals(Object)
, GetHashCode()
, ToString()
methods and ==
and!=
operators. With this new type (Record), we have an easier life comparing the properties of two different objects of the same type. It also provides the possibility to create immutable objects and some more synthetic sugars.
How To Create a Record
With record types, you can create immutable objects. Immutable means, you can’t change the values after creation, and that makes the object thread-safe. You can also make them non-immutable if you don’t need the functionality.
This first example is the way you create a non-immutable record:
Student sam = new Student()
{
FirstName = "Sam",
LastName = "Adam",
Age = 33
};
// It's ok to do change the LastName property since it's not immutable
sam.LastName = "Fadam";
public record Student
{
public string FirstName { get; set; }
public string LastName { get; set; }…