I would like check no null parameters are assigned to record fields and let the properties have comments. I have found out the following arrangement does the trick for comments, but I lack ideas to check for null parameters without turning this record into a class.
So, a question: Is it possible to check during runtime that nulls won't be assigned to record fields? If so, how could one do it while still using records?
public record Test(string TestString)
{
/// <summary>
/// This is one way to get a comment on record properties. Are there others?
/// </summary>
public string TestString { get; init; } = TestString;
}
The code is also as a gist here.
This is an addition, but maybe helps with the accepted answer and the comment of different code.
It was because the code in the gist did a null check like
public record Test(string TestString)
{
/// <summary>
/// This is one way to get a comment on record properties. Are there others?
/// </summary>
public string TestString { get; init; } = TestString ?? throw new ArgumentNullException();
}
For a reason or another, I didn't include this pondering in the original question if there's maybe a shorter way. :)
<edit: The .NET 6 ArgumentNullException.ThrowIfNull(obj) could be handy here (or ThrowHelper).
You have to handle checks during inline assignment, as you've already discovered in your gist.
One possibility is to call an extension method to wrap any behavior.
public record Test(string TestString)
{
/// <summary>
/// This is one way to get a comment on record properties. Are there others?
/// </summary>
public string TestString { get; init; } = ValidationExtensions.Validate(TestString);
}
public static class ValidationExtensions
{
public static string Validate(string input)
{
if (string.IsNullOrEmpty(input))
throw new NullReferenceException();
return input;
}
}
This will correctly throw during initialization of the record:
var x = new Test(null);