I've got a table with some nullable double fields. Working with LinqToSQL trying to use the field directly I get
Argument type System.Nullable is not assignable to parameter type double
How do I deal with this correctly?
I've got a table with some nullable double fields. Working with LinqToSQL trying to use the field directly I get
Argument type System.Nullable is not assignable to parameter type double
How do I deal with this correctly?
You can use
When you have a
Nullable<T>
and you need a value of typeT
. This will normalize anynull
to the default value ofT
, which will be 0.0 for a double. If you want something other than the default, you can work around it another way.The problem has nothing to do with Linq. It's got to do with conversion between
double
anddouble?
/Nullable<double>
.Implicit conversion from
double?
todouble
is not allowed:You can reference the double value directly:
This will throw a
NullReferenceException
if theNullable<T>
is null (that is,.HasValue
is false).You can cast it:
Again, you'll get an exception if the
Nullabl<T>
is null.You can use the null coalescing operator to assign a default value if the
Nullable<T>
is null:This, natch, avoids the NullReferenceException` problem.
You can use the ternary operator in the same vein as the null coalescing operator:
Finally, you can use regular conditional logic to follow an alternative path:
Those are about the options. Which is correct? Dunno. Depends on the your context.
There are two approaches.
Use nullable types such as double?. Your entity class can have a property of double? and your client code will work with the nullable type.
Write a wrapper around the assignment that chooses a safe default value if NULL is present. I like to use an extension method off the data record class and put a SafeConvert method there.
You can either cast it:
double yourVariable = (double)ValueFromDb
or you can just grab the Value of thedouble?
:double yourVaraible = ValueFromDb.Value
. Either is correct.