Home > Software engineering >  Foreach variable not null after check still gives warning
Foreach variable not null after check still gives warning

Time:12-22

See this sample:

var list = new List<string?>();

foreach (string item in list.Where(i => i != null))
{
    if (item.Length == 2)
    {
        ...
    }
}

In this sample, I get possible null reference in two places. The foreach variable and the dereferencing of Length in if. The second one I can easily fix by adding a dammit (null-forgiving) operator like this: item!.Length

Is there any way to do the same thing to the first one? I know that I can mark it as nullable string and check again but, I have already checked.

CodePudding user response:

When you apply filtering using Where, you eliminate all null values, but this doesn't change the type of values.
All you need is to cast the results after filtering to the proper type:

foreach (string item in list.Where(i => i != null).Select(x => x!))
  • Related