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?
The problem has nothing to do with Linq. It's got to do with conversion between double
and double?
/Nullable<double>
.
Implicit conversion from double?
to double
is not allowed:
double? foo ;
double bar = foo ;
You can reference the double value directly:
double? foo ;
double bar = foo.Value ;
This will throw a NullReferenceException
if the Nullable<T>
is null (that is, .HasValue
is false).
You can cast it:
double? foo ;
double bar = (double) foo ;
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:
double? foo ;
double bar = foo ?? -1.0 ;
This, natch, avoids the NullReferenceException` problem.
You can use the ternary operator in the same vein as the null coalescing operator:
double? foo ;
double bar = ( foo.HasValue ? foo.Value : -2 ) ;
Finally, you can use regular conditional logic to follow an alternative path:
double? foo ;
double bar ;
if ( foo.HasValue )
{
doSomething(foo.Value) ;
}
else
{
doSomething() ;
}
Those are about the options. Which is correct? I don't know. It depends on your context.
You can use
double value = theObject.TheProperty.GetValueOrDefault();
When you have a Nullable<T>
and you need a value of type T
. This will normalize any null
to the default value of T
, which will be 0.0 for a double. If you want something other than the default, you can work around it another way.
double value = theObject.TheProperty ?? 1d; // where 1 replaces any null
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