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");
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.
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.
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 .
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.
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"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With