152

Is there a nicer way of doing the following:
I need a check for null to happen on file.Headers before proceeding with the loop

if (file.Headers != null)
{
  foreach (var h in file.Headers)
  {
   //set lots of properties & some other stuff
  }
}

In short it looks a bit ugly to write the foreach inside the if due to the level of indentation happening in my code.

Is something that would evaluate to

foreach(var h in (file.Headers != null))
{
  //do stuff
}

possible?

5
  • 3
    You can have a look here: stackoverflow.com/questions/6937407/… Commented Jul 31, 2012 at 6:34
  • stackoverflow.com/questions/872323/… is another idea. Commented Jul 31, 2012 at 6:36
  • 1
    @AdrianFaciu I think that's completely different. The question checks if the collection is null first before doing the for-each. Your link checks if the item in the collection is null. Commented Jul 31, 2012 at 6:38
  • Similar to stackoverflow.com/q/3088147/80161 and stackoverflow.com/q/6455311/80161 Commented Oct 9, 2015 at 14:52
  • 1
    C# 8 could simply have a null-conditional foreach of some sort, i.e. syntax like this: foreach? (var i in collection) { } I think it's a common enough scenario to justify this, and given the recent null-conditional additions to the language it makes sense here to? Commented Oct 19, 2016 at 22:43

8 Answers 8

179

Just as a slight cosmetic addition to Rune's suggestion, you could create your own extension method:

public static IEnumerable<T> OrEmptyIfNull<T>(this IEnumerable<T> source)
{
    return source ?? Enumerable.Empty<T>();
}

Then you can write:

foreach (var header in file.Headers.OrEmptyIfNull())
{
}

Change the name according to taste :)

Sign up to request clarification or add additional context in comments.

5 Comments

to satisfy Roslyn this IEnumerable<T> source should be this IEnumerable<T>? source
@Pawel: Well that depends on the setting for nullable reference types - which didn't even exist in 2012. If you decide to go through every C# answer on Stack Overflow for 14 years and comment on every one of them that doesn't comply with an optional feature that didn't exist at the time, it's going to take you a very long time, with little tangible benefit.
I agree @Jon. I meant to improve (valuable) answer not to complain.
@Pawel: My point is that there are millions of such answers. Anyone using nullable reference types should be aware that they haven't always existed, and be able to change their code accordingly. Note that if I did change it as suggested, the code would fail to compile in non-NRE-enabled contexts... and I hate the idea of every C# answer affected by this requiring two different versions of every code snippet.
@JonSkeet man these comments made my day Go Get him SKeet!
114

Assuming that the type of elements in file.Headers is T you could do this

foreach(var header in file.Headers ?? Enumerable.Empty<T>()){
  //do stuff
}

this will create an empty enumerable of T if file.Headers is null. If the type of file is a type you own I would, however, consider changing the getter of Headers instead. null is the value of unknown so if possible instead of using null as "I know there are no elements" when null actually(/originally) should be interpreted as "I don't know if there are any elements" use an empty set to show that you know there are no elements in the set. That would also be DRY'er since you won't have to do the null check as often.

EDIT as a follow up on Jons suggestion, you could also create an extension method changing the above code to

foreach(var header in file.Headers.OrEmptyIfNull()){
  //do stuff
}

In the case where you can't change the getter, this would be my own preferred since it expresses the intention more clearly by giving the operation a name (OrEmptyIfNull)

The extension method mentioned above might make certain optimizations impossible for the optimizer to detect. Specifically, those that are related to IList using method overloading this can be eliminated

public static IList<T> OrEmptyIfNull<T>(this IList<T> source)
{
    return source ?? Array.Empty<T>();
}

4 Comments

@kjbartel's answer (at " stackoverflow.com/a/32134295/401246 " is the best solution, because it doesn't: a) involve performance degradation of (even when not null) degenerating the whole loop to LCD of IEnumerable<T> (as using ?? would), b) require adding an Extension Method to every Project, or c) require avoiding null IEnumerables (Pffft! Puh-LEAZE! SMH.) to begin with (cuz null means N/A, whereas empty list means, it's applicable but is currently, well, empty!, i.e. an Employee could have Commissions that's N/A for non-Sales or empty for Sales when they haven't earned any).
@Tom aside from one null check there's no penalty for the cases where the enumerator is not null. Avoiding that check while also ensuring that the enumerable is not null is impossible. The code above requires the Headers to a an IEnumerable which is more restrictive than the foreach requirements but less restrictive than the requirement of List<T> in the answer you link to. Which have the same performance penalty of testing whether the enumerable is null.
I was basing the "LCD" issue on the comment by Eric Lippert on Vlad Bezden's Answer in the same thread as kjbartel's Answer: "@CodeInChaos: Ah, I see your point now. When the compiler can detect that the "foreach" is iterating over a List<T> or an array then it can optimize the foreach to use value-type enumerators or actually generate a "for" loop. When forced to enumerate over either a list or the empty sequence it has to go back to the "lowest common denominator" codegen, which can in some cases be slower and produce more memory pressure....". Agree it requires List<T>.
@tom The premise of the answer is that file.Headers are an IEnumerable<T> in which case the compiler can't do the optimization. It is however rather straight forward to extend the extension method solution to avoid this. See edit
34

Frankly, I advise: just suck up the null test. A null test is just a brfalse or brfalse.s; everything else is going to involve much more work (tests, assignments, extra method calls, unnecessary GetEnumerator(), MoveNext(), Dispose() on the iterator, etc).

An if test is simple, obvious, and efficient.

3 Comments

You do make an interesting point Marc, however, I'm currently looking to lessen the indentation levels of the code. But I will keep your comment in mind when I need to take note of performance.
Just a quick note on this Marc.. years after I asked this question and need to implement some performance enhancements, your advice came in extremely handy. Thank you
It's been over 10 years since this question was asked. So my thought is Microsoft should give us some syntatic sugar to have the foreach do a null check. For example foreach (var item in myList?) { ... }. The compiler will then see the question mark and wrap an if (myList == null) statement around the foreach block. This would make it look cleaner, and the ? is used for a similar purpose as a null-conditional operator myList?.Select(...) currently.
31

Using Null-conditional Operator and ForEach() which works faster than standard foreach loop.
You have to cast the collection to List though.

   listOfItems?.ForEach(item => // ... );

3 Comments

Please add some explanation around your answer, stating explicitly why this solution works, rather than just a code one-liner
best solution for my case
by far the cleanest option
20

the "if" before the iteration is fine, few of those "pretty" semantics can make your code less readable.

anyway, if the indentation disturbs your, you can change the if to check:

if(file.Headers == null)  
   return;

and you'll get to the foreach loop only when there is a true value at the headers property.

another option I can think about is using the null-coalescing operator inside your foreach loop and to completely avoid null checking. sample:

List<int> collection = new List<int>();
collection = null;
foreach (var i in collection ?? Enumerable.Empty<int>())
{
    //your code here
}

(replace the collection with your true object/type)

2 Comments

Your first option will not work if there is any code outside the if statement.
I agree, the if statement is easy and cheap to implement compared to creating a new list, just for code beautification.
7

The best answer in the year 2022 should be:

foreach (var h in file.Headers ?? Enumerable.Empty<T>())
{
    //do stuff
}

Replace T with your data type. if file.Headers is an array, use Array.Empty<T>() instead of Enumerable.Empty<T>()

2 Comments

Will not compile if your collection is an interface. Enumerable.Empty<T>() or Array.Empty<T>() is still more versatile in 2022.
This gave me the idea to use: foreach (var h in file.Headers ?? [])
3

I am using a nice little extension method for these scenarios:

  public static class Extensions
  {
    public static IList<T> EnsureNotNull<T>(this IList<T> list)
    {
      return list ?? new List<T>();
    }
  }

Given that Headers is of type list, you can do following:

foreach(var h in (file.Headers.EnsureNotNull()))
{
  //do stuff
}

2 Comments

you can use the ?? operator and shorten the return statement to return list ?? new List<T>;
@wolfgangziegler, If I understand correctly the test for null in your sample file.Headers.EnsureNotNull() != null is not needed, and is even wrong?
0

For some cases I'd prefer slightly another, generic variant, assuming that, as a rule, default collection constructors return empty instances.

It would be better to name this method NewIfDefault. It can be useful not only for collections, so type constraint IEnumerable<T> is maybe redundant.

public static TCollection EmptyIfDefault<TCollection, T>(this TCollection collection)
        where TCollection: class, IEnumerable<T>, new()
    {
        return collection ?? new TCollection();
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.