What’s new in C# 9?
In C# 9, Records are the most important new feature. Records are as immutable classes and it has the tuple like feature. Using records, it is easy to use small types and take advantage of type safety throughout the application.
Records enable you to create immutable types. It will store a small amount of data.
The following example illustrates the example of a record. It stores the information from the login view.
Public record UserLogin(string user Name, string user Password);
Following class and above records are semantically similar to each other.
Public class UserLogin
{
Public UserLogin(string user Name, string user Password)
{
UserName = user Name,
UserPassword = user Password
}
Public UserName{ get; init;}
Public UserPassword{ get; init;}
}
Init is a new keyword that is an alternative to the set. Where set allows you to assign to a property at any time whereas init allows you to assign to a property only during object construction. Any type can use the init keyword.
Record equality is based on content and class equality is based on object identity. Records provide the GetHashCode() implementation which is based on record content. Records provide an IEquatable implementation and it uses the unique GetHashCode() behavior.