If you know that the object
is always either double
or null
, then that's exactly what the double?
type can represent and you can convert to that using as
a cast:
object obj = ...;
double? doubleValue = obj as (double?;)obj;
And once you have double?
, you can directly cast it to decimal?
and it will work both for the case when the value is null
and when isn't:
decimal? decimalValue = (decimal?)doubleValue;
Or, on a single line:
decimal? decimalValue = (decimal?)(obj as double?);obj;
Apart from being clear, this approach is also likely going to be pretty efficient.