Paul_87
Paul_87

Reputation: 117

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.

Upvotes: 0

Views: 209

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460068

Your check doesn't make sense and also forgets one important.

  • DataSet.Tables also can't be null because it's a readonly property, you can't assign null, so the second check is pointless.
  • dataSet.Tables[0].Rows can't be null because it's a readonly property, you can't assign null, so the last check is redundant.

But you forgot that the DataSet could be empty, so doesn't contain any DataTables. In that case your if throws an exception at dataSet.Tables[0].

I would use:

int? firstTablesRowCount = dataSet?.Tables.Cast<DataTable>().FirstOrDefault()?.Rows.Count;
if (firstTablesRowCount.GetValueOrDefault() == 0)
{
    Console.WriteLine($"Error at {nameof(dataSet)}");
}

This ensures that the DataSet isn't null and contains tables and that the first table contains rows.

Upvotes: 4

horotab
horotab

Reputation: 683

Try

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

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

Upvotes: 2

Related Questions