Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

147
Visualizações
Foreach variable not null after check still gives warning

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.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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!))
over 4 years ago · Santiago Trujillo Relatório

0

Unfortunately the Where predicate doesn't modify the caller's view of whether items in the enumerable are null or not.

The approach given by Dmitry involves additional runtime overhead due to the use of an extra Select call.

You can avoid that overhead via this extension method:

public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> source) where T : class
{
    foreach (T? item in source)
    {
        if (item != null)
            yield return item;
    }
}

Your code then becomes:

foreach (string item in list.WhereNotNull())
{
    if (item.Length == 2)
    {
        ...
    }
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda