EliasMP EliasMP - 1 year ago 68
C# Question

How to recover double´s null coming from DB?

I have a table with a few fields, one of them is a Double type field which can contains null values...

Using ADO and SQLDATAReader I recover that field in a variable. I defined this variable as a: Double, Double?, double, double?... and I got the value (coming from de SQLDataReader) using GetValue (and doing a cast) or using a GetDouble... each one is crashing when the value is null.

The only this is working is defining this variable as a object, but I dont want it. Thinking in advance could be hard times handle this type in my project...

Quote: I have to differentiate the case when this value is 0 or null...

Any idea guys?


Object.DoubleValue= (Double?)Datos.GetDouble(1);
Object.doubleValue= (double?)Datos.GetDouble(1);

Not working.

Object.ObjectValue= Datos.GetValue(1);


Answer Source

Unfortunately there's no out of the box method. But you could tweak it with an extension method like this:

(be aware its just a rough prototype that works in your case, but probably needs some checks and constraints etc)

public static class Helpers
    public static T GetSmartValue<T>(this SqlDataReader r, int ordinal)
        dynamic value = r.GetValue(ordinal);
        if (value == DBNull.Value)
            value = null;
            return value;

        return (T) value;

then in your code

var x = yourReader.GetSmartValue<double?>(1);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download