17

I have a database query which will either return NULL or a boolean (bit) value.

I wish to store this value in a variable of type Nullable<bool> in C#.

I can't seem to find an acceptable mix of explict casts and conversions that do this in a simple way without Exceptions being thrown.

Can it be done in one readable line?

EDIT: Code as requested

private Nullable<bool> IsRestricted;
...//data access
IsRestricted = (bool?)DataBinder.GetPropertyValue(dataObj, "IsRestricted");

or perhaps

IsRestricted = (bool?)(bool)DataBinder.GetPropertyValue(dataObj, "IsRestricted");
Widor
  • 13,003
  • 7
  • 42
  • 64

5 Answers5

13

assuming you have a datareader dr:

bool? tmp = Convert.IsDBNull(dr["dbnullValue"]) ? null: (bool?) dr["dbnullValue"];

---ADDED----

or maybe you can use the ?? if you don't have to check for DBNull but i'm not sure compiler will like this (i cannot test it now)

bool? tmp = dr["dbnullValue"] ?? (bool?) dr["dbnullValue"];
giammin
  • 18,620
  • 8
  • 71
  • 89
6

You could write value as bool?.
This will return null if value is not of type bool.

Note that this is somewhat inefficient.

Community
  • 1
  • 1
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • I don't like this, because it's unsafe. If something changes and the result is some other type, I think exception is much better than `null`. – svick Jan 30 '13 at 17:24
  • 2
    @svick: Then you need more complexity: `value is DBNull ? null : (bool?)value` – SLaks Jan 30 '13 at 17:28
0
 while (reader.Read()) {
    bool? IsRestricted = (reader.IsDBNull(reader.GetOrdinal("IsRestricted"))) ? (null) : ((bool)reader.GetOrdinal("IsRestricted")));
 }
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
0

I use extension methods for this issue.

var isRestricted = dataRecord.GetNullableValue<bool>("IsRestricted");

There is code of GetNullableValue method:

    public static Nullable<TValue> GetNullableValue<TValue>(
        this IDataRecord record, 
        string name) where TValue : struct
    {
        return record.GetValue<TValue, Nullable<TValue>>(name);
    }

And there is also a simple code for GetValue method:

        private static TResult GetValue<TValue, TResult>(
        this IDataRecord record,
        string name)
    {
        var result = record[name];
        return !result.Equals(DBNull.Value) ? (TResult)result : default(TResult);
    }
Ilya Palkin
  • 14,687
  • 2
  • 23
  • 36
0

You can just do the following

bool? myNullableBoolean = SqlConvert.ToType<bool?>(reader["myNullableBooleanColumn"]);

JB's
  • 606
  • 13
  • 30