Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a neat way to compare nullable and dbnullable objects?

Tags:

c#

I have code like this:

foreach (DataRow row in dataTable.Rows)
{
        if ((string)row["Forename"] != record.Forename)
        { 
             // Do something
        }
}

Works great but if row["Forename"] is null in the database, it is actually DBNull here and it can't cast DBNull to a string, or perform the comparison between DBNull and string. Some values are also nullable<int>, and it can't compare DBNull with int?

Is there a helper method to let me do nice comparisons or do I have to write an extension method myself?

like image 365
NibblyPig Avatar asked Jun 02 '14 16:06

NibblyPig


2 Answers

You can use the DataRow.Field extension method which supports nullable types:

foreach (DataRow row in dataTable.Rows)
{
    int? id = row.Field<int?>("ID");
    if(id.HasValue)
    {
        Console.Write("ID: " + id.Value);
    }
}

Since string is a reference type it will be null by default. You can use DataRow.IsNull instead to check whether it is DBNull.Value or not:

foreach (DataRow row in dataTable.Rows)
{
    if(row.IsNull("Forename"))
    {
        // ...
    } 
    else
    {
        string foreName = row.Field<string>("Forename");
        Console.Write("ForeName: " + foreName);
    }
}
like image 135
Tim Schmelter Avatar answered Oct 22 '22 05:10

Tim Schmelter


You can write your own extension method like this

public static T GetField<T>(this DataRow row,string columnName)
{
    object value = row[columnname];
    return (value != DbNull.Value)? (T)value : default(T);
}

Then you can use

if (row.GetField<string>(columnname) != record.Forename)
{ 
     // Do something
}

This extension should support nullable types also

var value = row.GetField<int?>(columnname);

The only difference with DataRowExtension.Field and our implementation is that it will throw exception when we're trying to cast DbNull.Value to any value type(except nullable type) in such case this method will return default value.

like image 34
Sriram Sakthivel Avatar answered Oct 22 '22 05:10

Sriram Sakthivel