How to determine if DataTable is null, not initialized

advertisements

I have a method that does some work on a DataTable e.g.

private void MyMethod(DataTable table)
{
    if(table.Rows.Count > 0)
    {
       //  do some work
    }
 }

However, if the method receives a null datatable from the application it serves I get an 'Object reference not set to an instance of an object' error.

I have also tried . . .

if(table.IsInitialized) { }

and

if(table != null) {  }

but I get the same error message.

How do I test to see if the incoming datatable is instantiated and not null please?

The DataTable is coming from a cast of a datagrid in a WinForms app i.e.

DataTable table = (DataTable)datagridview.DataSource;

So the issue arises if the original datagridview is empty.


You get the "reference not set to a instance of objeect" exception if you got a case like this:

object someObject = null;
//Throws an exception. You try to call a instance function without specify the instance
someObject.ToString();

So either table is null or rows returns null. Prior to C# 6.0 you ahve to go the hard way:

if(table != null && table.Rows != null && table.Rows.Count > 0)

I asumed count was not a nullable Integer. If it was, you have to check for it being null too of course.

At least for debugging, you might want to write that code a bit more verbose with a "one operation per line" rule. That would help you localise wich operation exactly returns null. And the JiT will most likely cut out the temporary variables outside of debug runs anyway.

//If table is null, exception here
var Row = table.Row;
//If Row is null, Exception here.
var Count = Row.Count;
//Nothing is null. Continue.
if(Count > 0);

With C# 6.0, you got the new Null conditional operator to write it a bit shorter: https://msdn.microsoft.com/en-us/library/dn986595.aspx It is still the same code, however.