Reputation: 117
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
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
Reputation: 683
Try
if(dataSet?.Tables?.FirstOrDefault()?.Rows == null) {}
FirstOrDefault()
returns the first entry or null if there is none.
Upvotes: 2