Search code examples
c#null-check

A better way to write null reference with return value in c#


Is there a better way to write this null check? I'm checking a table from a DataSet for nulls.

if (dataSet == null || dataSet.Tables == null || dataSet.Tables[0].Rows == null)
{
    Console.WriteLine($"Error at {nameof(dataSet)}");
    return vatPeriodList;
}

I'm working in ADO.NET.


Solution

  • Try

    if(dataSet?.Tables?.FirstOrDefault()?.Rows == null) {}
    

    FirstOrDefault() returns the first entry or null if there is none.