1

I would like to check the results from a C# database call to make sure ..

  1. The DataTable returned is NOT NULL
  2. The DataTable has rows (DataTable.Rows.Count > 1)

If either of these conditions are true I want to return the same exception as this type of result is not expected, there should always some records. Is there a way to do this without repeating the throw exception statement?

if (myDataTable != null) { if (myDataTable.Rows.Count > 0) { myRow = myDataTable.Rows[0]; } else { throw new Exception("Problem obtaining data"); } } else { throw new Exception("Problem obtaining data"); } 

I don't need to differentiate between these exceptions for my purposes.

2 Answers 2

4

Maybe

if (myDataTable != null && myDataTable.Rows.Count > 0) { myRow = myDataTable.Rows[0]; } else { throw new Exception("Problem obtaining data"); } 

You don't need to nest the if statements

Sign up to request clarification or add additional context in comments.

3 Comments

In C# 6 you could write if (myDataTable?.Rows.Count >0) and avoid the null check
Marked as answer because I like the idea of having the exception in the else. Answer from @sebastien was also correct. Sorry.. had to choose one.
It might be worth adding a small explanation about short-circuit evaluation of && and || for those who are unfamiliar with it.
3

You could simply write:

if (myDataTable == null || myDataTable.Rows.Count == 0) { throw new Exception("Problem obtaining data"); } myRow = myDataTable.Rows[0]; 

1 Comment

I think the null check is inverted :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.