Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for 'lazy loaded' null IEnumerable in c#?

I've simplified a piece of a deferred execution code, but how on earth do you check the following is not null/empty without wrapping it in a try/catch?

    string[] nullCollection = null;
    IEnumerable<string> ienumerable = new[] { nullCollection }.SelectMany(a => a);

    bool isnull = ienumerable == null; //returns false
    bool isany = ienumerable.Any(); //throws an exception
like image 252
maxp Avatar asked Apr 11 '17 08:04

maxp


People also ask

Does IEnumerable support lazy loading?

IEnumerable doesn't support lazy loading. IQueryable support lazy loading. Hence it is suitable for paging like scenarios.

How do I know if IEnumerable has an item?

enumerable. Any() is the cleanest way to check if there are any items in the list.

Can IEnumerable contain null?

An object collection such as an IEnumerable<T> can contain elements whose value is null.


2 Answers

You just need to make your lambda more resilient to null entries:

IEnumerable<string> ienumerable = new[] { nullCollection }
    .SelectMany(a => a ?? Enumerable.Empty<string>());

bool isany = ienumerable.Any(); // Sets isany to 'false'
like image 97
RB. Avatar answered Sep 19 '22 18:09

RB.


You cannot do that, because that's the same as asking "how can I tell that method will not throw NullReferenceException without invoking it?". Having no other clues the only way is actually invoke such methods and observe the result. Enumerating IEnumerable is just invoking bunch of MoveNext calls on it's enumerator, and any such call might throw any exceptions.

like image 25
Evk Avatar answered Sep 18 '22 18:09

Evk