I have an entity which I use in my EntityFramework model.
public class Entity
{
public int Id { get; set; }
public string Value { get; set; }
}
After enabling nullable reference types compiler gives me a warning:
Warning CS8618 Non-nullable property 'Value' is uninitialized.
I know that this property is not nullable in the database and its safe.
Is there any way to mark this property as safe other than disabling the warnings in the class with #pragma warning disable
?
My first instinct was trying to mark the type as safe with !
like this
public string! Value { get; set; }
but that didn't work.
Nullable reference types are a compile time feature. That means it's possible for callers to ignore warnings, intentionally use null as an argument to a method expecting a non nullable reference. Library authors should include runtime checks against null argument values.
The nullable reference types are super useful. In my case, not surprisingly, it has decreased the amount of null reference exceptions in the code. No doubt that it improves the quality of my code. In the future, I am ready to use it as extensively as I do now and I recommend that you try it too if you have not yet.
Nullable type in C# is used to assign null values to value type variables like to the variables of type int, float, bool, etc., because they cannot store null values. On the other hand, we cannot use nullable with string or any other reference type variable because it can directly store null value.
See an answer to my similar question. If you ensure by some business rules the non-nullability (validation in my case), it is better to tell to consumers of your class that some property will be never null by using the non-nullable property and handle compiler warning by using this construct.
public class Entity
{
public int Id { get; set; } = null!;
public string Value { get; set; } = null!;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With