How To Change the Behavior of a C# Record Constructor
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: public class StringValidator { public string InputString { get; } public StringValidator(string inputString) { if (string.IsNullOrEmpty(inputString)) throw new ArgumentNullException(nameof(inputString)); InputString = inputString; } } 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...