Search code examples
c#castingdatatablenullable

casting nullable decimal from DataTable


I have a DataTable table. from that table I read value from a column, which is typeof(decimal). I try to cast this value to decimal? dec. When value is null, I get an exception. I tried it this way:

decimal? dec= row["myRow"] == null ? null : (decimal?)row["myRow"]; 
//this thorws "Specified cast is not valid." Exception

decimal? dec= myRdr["myValue"] == DBNull.Value ? null : (decimal?)myRdr["myValue"]; 
//this does NOT throw an Exception?? 

I tried the second solution when reading from SQL data table using SQLDataReader and it worked with no problems.


Solution

  • As said in comments, DBNull.Value and null are not same thing. So when you are writing:

    decimal? dec= row["myRow"] == null ? null : (decimal?)row["myRow"]; 
    

    you are trying doing this:

    if(DBNull.Value == null)
    {
        return null;
    }
    else
    {
        return (decimal?)row["myRow"];
    }
    

    which is false so the second part (in else)

    (decimal?)row["myRow"];
    

    is executed. This throws an exception.

    But in second case:

    if(DBNull.Value == DBNull.Value)
    {
        return null;
    }
    else
    {
        return (decimal?)row["myRow"];
    }
    

    is true so the cast statement is not executed and null is returned.