Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle DBNull in C#

Is there a better/cleaner way to do this?

int stockvalue = 0;
if (!Convert.IsDBNull(reader["StockValue"]))
    stockvalue = (int)reader["StockValue"];
like image 410
Andreas Avatar asked Mar 12 '10 13:03

Andreas


People also ask

How do you handle database NULL values in C#?

IsNullOrEmpty() Method of C# If any string is not assigned any value, then it will have Null value. The symbol of assigning Null value is “ “or String. Empty(A constant for empty strings). This method will take a parameter that will be of System.

What is DBNull error?

If the return value from the database for that column is NULL , this translates to DBNull. Value in code. You need to check for this as it won't successfully cast to byte[] .

Is DBNull a value?

Null is similar to zero pointer in C++. So it is a reference which not pointing to any value. DBNull. Value is completely different and is a constant which is returned when a field value contains NULL.

How do you handle a DBNull?

DBNull represents a nonexistent value returned from the database. In a database, for example, a column in a row of a table might not contain any data whatsoever. That is, the column is considered to not exist at all instead of merely not having a value. A DBNull object represents the nonexistent column.


3 Answers

The shortest (IMHO) is:

int stockvalue = (reader["StockValue"] as int?) ?? 0; 

Explanation:

  • If reader["StockValue"] is of type int, the value will be returned, and the "??" operator will return the result
  • If reader["StockValue"] is NOT of type int (e.g. DBNull), null will be returned, and the "??" operator will return the value 0 (zero).
like image 99
Philippe Leybaert Avatar answered Sep 22 '22 08:09

Philippe Leybaert


The way I handle this is

int? stockvalue = reader["StockValue"] as int?; 

Very simple, clean and one line. If for some reason I absolutely can't have a null value (which I find poor reasoning for usually since I'd rather know if a value has meaning or if it was unitialized for a primitive type) I would do:

int stockvalue = (reader["StockValue"] as int?).GetValueOrDefault(-1); 
like image 37
Chris Marisic Avatar answered Sep 21 '22 08:09

Chris Marisic


I wrote an extension method several days ago. By using it you could just do:

int? stockvalue = reader.GetValue<int?>("StockValue");

Here's the extension method (modify to fit your needs):

public static class ReaderHelper
{
    public static bool IsNullableType(Type valueType)
    {
        return (valueType.IsGenericType &&
            valueType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)));
    }

    public static T GetValue<T>(this IDataReader reader, string columnName)
    {
        object value = reader[columnName];
        Type valueType = typeof(T);
        if (value != DBNull.Value)
        {
            if (!IsNullableType(valueType))
            {
                return (T)Convert.ChangeType(value, valueType);
            }
            else
            {
                NullableConverter nc = new NullableConverter(valueType);
                return (T)Convert.ChangeType(value, nc.UnderlyingType);
            }
        }
        return default(T);
    }
}
like image 26
Vivek Avatar answered Sep 19 '22 08:09

Vivek