Search code examples
c#nullable-reference-types

Explicit nullable types and where != null


When using the new explicit nullable reference types features in C# 8.0 (all types must be explicity declared as nullable if they are to be set to null https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references ), how do you handle the following situation:

Say you have some function that returns an IEnumerable of Something?

var result = aFunction()
         .Where(data => data != null)
         .Select(data => data.Id).ToList();

the data.Id is shown as an error (I have warnings as errors turned on):

enter image description here

because it can be null, even though it is checked to be not null by the Where. I don't want to have to supress the error in this case, is there a way to handle this syntactically?


Solution

  • The compiler is not "smart" enough to detect that the argument to Select() cannot be null in this case, as it only does static code analysis. For situations like these, the ! notation was introduced with nullable reference types. Applying an exclamation mark to an object tells the compiler to "shut up" about nullability warnings.

    var result = aFunction()
             .Where(data => data != null)
             .Select(data => data!.Id).ToList();
    

    This means that the compiler will not generate a warning that data could be null. This is helpful in all cases where you know that the value is not null, but the compiler (e.g. due to the complexity of the code) doesn't properly detect that.

    Note that this really only removes the warning. If the value is, in fact, null, the code will behave as previously, so it would throw a NullReferenceException.