Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is null checking required for IEnumerable object?

var selectedRows = from drow in ugTable.Rows
                         .Cast<Infragistics.Win.UltraWinGrid.UltraGridRow>()
                         .Where(drow => drow != null && drow.Selected) 
                   select drow;

if(selectedRows.Count()==1){//do something with selected rows}

From the above statement, do i need to check Null for the selectedRows variable? selectedRows is an IEnumerable variable.

like image 509
Tanya Avatar asked May 05 '11 05:05

Tanya


People also ask

Can an IEnumerable be null?

An object collection such as an IEnumerable<T> can contain elements whose value is null. If a source collection is null or contains an element whose value is null , and your query doesn't handle null values, a NullReferenceException will be thrown when you execute the query.

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.

How do I empty my IEnumerable?

Clear() will empty out an existing IEnumerable. model. Categories = new IEnumerable<whatever>() will create a new empty one. It may not be a nullable type - that would explain why it can't be set to null.


2 Answers

You do not need to check if selectedRows is null. The returned IEnumerable<> might be empty, but it will never be null.

As an aside, I'd suggest you simplify your code by writing:

var selectedRows
    = ugTable.Rows.Cast<Infragistics.Win.UltraWinGrid.UltraGridRow>()
                  .Where(drow => drow != null && drow.Selected);

Which is shorter and equivalent.

like image 126
Frédéric Hamidi Avatar answered Oct 11 '22 18:10

Frédéric Hamidi


The LINQ query will return an empty list (0 items), if there are no matches on the where.

So, no need to check for null.

like image 42
Oded Avatar answered Oct 11 '22 18:10

Oded