Search code examples
c#foreachnull-object-pattern

c# what object literal could stop a foreach loop from looping?


I know I could wrap the entire foreach loop in an if statement, but I'm wondering if there's some object literal value replacement for new List<string>() so that the foreach skips executing when myList is null? In Javascript I could simply put [] after a coalesce to refer to an empty set that would stop the foreach loop.

List<string> myList = null;

foreach (var i in myList ?? new List<string>() )
    i.Dump();

Unnecessary background information that does not change the answer: List<Entity>() is my actual list that comes from ASP.NET MVC data binding, so I don't control creating it. I used the Entity Framework database models (POCOs) as an input to the Controller method like you would use a control function, setting parameters of the function to flow data to a table. The POCO comes from the database, so I don't control that either.

Just looking for some sort of empty object literal I could use to avoid running the loop without creating a new object.

I really think it's a C# flaw to throw an exception when myList is null. If it's null, there's nothing to do, so the loop should skip over.


Solution

  • Use Enumerable.Empty<string>().

    See C# EmptyIfNull extension for any IEnumerable to return empty derived type or Linq method to transform nulls into empty IEnumerable<T>? for extension methods you could use if you need to make this check often.