Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I cast from DBNull to a Nullable Bool in one line?

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");
like image 318
Widor Avatar asked Jan 30 '13 17:01

Widor


People also ask

What is object Cannot be cast from DBNull to other types?

Object cannot be cast from DBNull to other types since value in Date column datarow is null. Hi. There's a flaw in your condition. You are checking if it is empty after you converting it to a date, so that's kind of pointless considering it will error if the value is not a date or empty.

What is the difference between DBNull and null?

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.

Can bool be nullable?

You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool , variable can only be either true or false .

What is DBNull type?

The DBNull class represents a nonexistent value. 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.


1 Answers

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"];
like image 89
giammin Avatar answered Oct 23 '22 20:10

giammin