Will a for loop or foreach loop throw an exception in C# if the DataTable is null or contains no rows?

In C#, when working with a DataTable, you won’t get an exception from a for loop or foreach loop if the DataTable itself is not null but has no rows. However, if the DataTable is null, then trying to loop through it will throw a NullReferenceException.

Let’s break it down:
Safe: Empty DataTable (Not Null)

DataTable dt = new DataTable(); // empty, not null

foreach (DataRow row in dt.Rows)
{
    // This won't execute because dt.Rows.Count == 0
}

No exception will occur. The loop just won’t run.


Unsafe: Null DataTable

DataTable dt = null;

foreach (DataRow row in dt.Rows) // ❌ This will throw NullReferenceException
{
    // Exception occurs before even entering the loop
}

Safe check before looping

To safely handle both cases:

if (dt != null && dt.Rows.Count > 0)
{
    foreach (DataRow row in dt.Rows)
    {
        // Process row
    }
}

Or, if you only care about null (not rows being empty):

if (dt != null)
{
    foreach (DataRow row in dt.Rows)
    {
        // Will safely skip if there are no rows
    }
}

if you’re checking DefaultView, Select(), or filtered rows — those can behave slightly differently.

1. ✅ DataTable.DefaultView

  • DefaultView is never null (even if DataTable is empty).

  • DefaultView.Count represents the number of visible (filtered) rows.

Example:

DataTable dt = new DataTable();
// Assume dt is initialized but has no rows

foreach (DataRowView drv in dt.DefaultView)
{
    // This is safe. Won’t throw, just won’t execute.
}

🟢 Safe: Won’t throw an exception — loop simply won't run if there are no rows.


2. ✅ DataTable.Select()

  • Select() returns a DataRow[] array.

  • If there are no matching rows, it returns an empty array, not null.

Example:

DataRow[] rows = dt.Select("SomeColumn = 'value'");

foreach (DataRow row in rows)
{
    // Safe, even if rows.Length == 0
}

🟢 Safe: Won’t throw an exception — the loop won’t run if no match.


3. ⚠️ Filtered rows using DefaultView.RowFilter

  • When you set a filter using DefaultView.RowFilter, the view updates to only show matching rows.

  • Still safe to iterate, but if you expect data and it’s filtered out, the result may be empty (not an exception though).

Example:

dt.DefaultView.RowFilter = "SomeColumn = 'value'";

foreach (DataRowView drv in dt.DefaultView)
{
    // Safe — executes only if any rows match the filter
}

🟢 Safe: No exception — just an empty loop if nothing matches.


❗ Summary

SourceNull possibilityThrows in foreach?Safe?
DataTable.RowsYes (if dt is null)✅ Throws if null❌ Unsafe without null check
dt.DefaultViewNo❌ Never throws✅ Safe
dt.Select()No (returns empty array)❌ Never throws✅ Safe
dt.DefaultView.RowFilterNo❌ Never throws✅ Safe
0
Subscribe to my newsletter

Read articles from Abdullah Al Masum directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Abdullah Al Masum
Abdullah Al Masum