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");
I use extension methods for this issue.
There is code of GetNullableValue method:
And there is also a simple code for GetValue method:
You could write
value as bool?
.This will return
null
ifvalue
is not of typebool
.Note that this is somewhat inefficient.
assuming you have a datareader dr:
---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)