Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

148
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda