Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a Warning about a nullable type issued, even though there can be no null value?

Why do I get a Warning in the line of list2? I filtered out all null values here. The warning states, that in the select method a null value might be dereferenced.

#nullable enable

using System.Collections.Generic;
using System.Linq;

namespace TestNamespace
{
    public class Test
    {
        public Test()
        {
            List<string?> testList = new List<string?>()
            {
                "hallo",
                null
            };

            IEnumerable<string> list2 = testList.Where(x => x != null).Select(x => x.Replace("A", "")); // warning
            IEnumerable<string> list3 = testList.Where(x => x != null).Select(x => x != null ? x.Replace("A", "") : ""); // no warning
        }
    }
}

This is the warning I get in the line of list2: Warning about nullable type

In the line of list3 no warning is issued, but the check in the Select-Statement will always be pointless.

like image 841
ykasur Avatar asked Jan 31 '26 00:01

ykasur


2 Answers

You get a warning because the type in the enumerable is still the nullable string?.

I suppose it's possible another thread changes the hallo entry to null during the enumeration, but more likely the compiler is just not sophisticated enough to understand you have filtered out any possible null values ahead of time.

You can use .Cast<string>() after filtering out the null values to change the type in the enumerable, or you can use a null-forgiving operator to remove the warning.


For fun, I also wrote this:

public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> items)
{
    foreach(var item in items) 
    {
        if (item is object)
        {
           yield return item;
        }
    }
}

See it work here:

https://dotnetfiddle.net/F8iQ0I

like image 78
Joel Coehoorn Avatar answered Feb 01 '26 12:02

Joel Coehoorn


Even though you using the Where condition to filter, the Select statement stands alone.

The source type for the select statement is still IEnumerable<string?> hence the warning.

Example

For your reference.

As for the second scenario, In this case, No warning because of this

This set of warnings alerts you that you're dereferencing a variable whose null-state is maybe-null.

We know for sure that x won't be null because of the x != null in Select.

like image 32
ShubhamWagh Avatar answered Feb 01 '26 14:02

ShubhamWagh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!