Is null checking required for IEnumerable object?

Tanya picture Tanya · May 5, 2011 · Viewed 16.4k times · Source
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.

Answer

Fr&#233;d&#233;ric Hamidi picture Frédéric Hamidi · May 5, 2011

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.