'Intended or less-wrong pattern for using non-nullable types of class properties

There's a great question here about nullable types:

Non-nullable property must contain a non-null value when exiting constructor. Consider declaring the property as nullable

Which has some great ways to overcome the warning, but I'm interested in the reasoning behind using any particular method.

I'm working with EF Core to craft an API. I'm being careful to never instantiate a model class without having the correct data, but the class doesn't know that so we get the typical "Non-nullable property must contain..." warning.

At least in my head, I want the null reference error to happen when appropriate, to be passed back to a client or to prevent inappropriately null/empty values being passed down.

Example: a "this field required situation", if it somehow gets past the front-end validation an exception should be thrown, and the exception handler returns an appropriate BadRequest response to the client. I'm currently doing this rather than handling each individual property with an explicit validation method, at least for required properties.

It's seems disingenuous to try to accommodate the possibility of a null being passed in by:

  • Declaring the property nullable: this property really shouldn't be nullable, so I would just be allowing it in order to suppress the warning, which may cause functional issues or extraneous considerations elsewhere.
  • Setting a null-forgiveness null!: which seems appropriate in some situations, but not anywhere where the property should be set and not-null at all times.
  • Setting a default such as string.Empty: again appropriate in some situations, but not where the property should be set to something substantial and meaningful.
  • Setting up a constructor: this seems a lot of extra work to do essentially the same thing, and I'm not certain this overcomes the warning as much as moves it.
  1. Am I wrong in wanting to use an exception to catch when an instantiation doesn't set or sets null a non-nullable property? I only question this because of the warning about the non-nullable property.
  2. Is there some other pattern I'm unaware of that would be more appropriate, and that's why the warning?
  3. Am I just putting too much stock in the warning?


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source