Home > Software engineering >  Nullable type producing warnings since project has enabled nullable reference types
Nullable type producing warnings since project has enabled nullable reference types

Time:12-02

I only get the warnings after I enable nullable reference types, but the specific example is actually the good old Nullable<T> type:

var nullableItems = new List<int?>();

var actualNonNullValues = nullableItems.Where(x => x.HasValue)
                                       .Select(x => x.Value)
                                       .ToList();

So I sort out all the nulls and only want the actual non-null items. However, the part .Select(x => x.Value) will give me a compiler warning about x maybe being null here. Logically, it is not, but for the compiler, the type has not yet changed and it's still a int?.

I know I can tell the compiler to shut up by just applying an ! to the x, but it seems like I cheated. In other languages I use, having to fall back onto this is considered bad practice and means you did something wrong.

What are my other options? Can I do better than just use an ! here?

CodePudding user response:

In the Select(x => x.Value), x is of type int? so compiler promptly warns you that calling .Value on that type might throw.

This does not make much sense since you already checked for nullability in the .Where(x => x.HasValue). Unfortunately, C# compiler does not currently understand that the Select will receive only non-null values as its context has no understanding of the Where method semantics.

Only option you have is ! as it says "I know what I'm doing here."

There is a language issue tracking this: https://github.com/dotnet/csharplang/issues/3951

  • Related