Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mark a NonNullable reference property as safe? [duplicate]

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.

like image 348
ctyar Avatar asked Feb 20 '19 09:02

ctyar


People also ask

What is a nullable reference type?

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.

Should you use nullable reference types?

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.

What is nullable string C#?

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.


1 Answers

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!;
}
like image 97
Karel Kral Avatar answered Sep 27 '22 16:09

Karel Kral