Records are a new feature in C# 9. Records are special classes that borrow from Structs in that they have value-based equality. You could look at them as a hybrid between the two categories of types. They are more or less immutable by default and have syntax sugar to make declaration easier and more concise. However, the syntax sugar can obscure more standard tasks like changing the behavior of the default constructor. You will probably need to do this for validation in some cases. This article shows you how to achieve this.
Take this simple example class:
It’s clear that if the consumer attempts to create an instance of this class without a valid string, they will get an exception. The standard syntax for creating a record looks like this:
It’s friendly and concise, but it’s not immediately clear how you would validate the string. This definition tells the compiler that there will be a property named
InputString, and the constructor will pass the value to that property from a parameter. We need to remove the syntax sugar to validate the string. Fortunately, this is easy. We do not need to use the new syntax to define our records. We can define the record similar to a class but change the keyword class to record.
Unfortunately, this means we cannot use the non-destructive mutation.
This allows us to harness some of the benefits of immutability while still performing basic tasks like validating the input of constructors. Try not to put too much logic in the constructor, but you will find that this sometimes necessary.