When retreiving data with an api and saving it in a DTO, some values are nullable: null on initial class initialization but VS also warns you for this. For example, an employee:
public class EmployeeModel
{
public Guid Id { get; set; }
public int EmployeeNumber { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
}
In practice, this might never happen because of database constraints obligating the user to enter all properties. But on creating the class and using it in the code, the FirstName might be null. How to deal with this? Two questions.
1) How to check if a class has no null values?
Imagine the class has 10 string propeties and 2 int properties. To check if one of them is a null, I need 12 if statements. Which of course could be done in a separate method, see next question, but is still alot of code. And on adding a property, it must be manually added. And checking it outside a method is not enough without the NotNull
as used in ArgumentNullException.
2) In case of null values, should ArgumentNullExceptions be used or a custom PropertyNullException? A property is not an argument, but a custom PropertyNullException is identical to ArgumentNullException part from the name. Simplified version:
public class PropertyNullException : Exception
{
public string PropertyName { get; }
public PropertyNullException(string propertyName)
: base($"Property {propertyName} is null.")
{
PropertyName = propertyName;
}
public PropertyNullException(string propertyName, Exception inner)
: base($"Property {propertyName} is null.", inner)
{
PropertyName = propertyName;
}
public static void ThrowIfNull([NotNull] object? property, string propertyName)
{
if (property is null)
{
throw new PropertyNullException(propertyName);
}
}
}
Another option would be to, after a class creates the DTO's from the api, check all the properties for null
/Guid.Empty
/0
values? Or, of course, I'm doing something else wrong.