Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!