Skip to main content
deleted 11 characters in body
Source Link
svick
  • 24.3k
  • 4
  • 52
  • 89

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 asa 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.

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:

object obj = ...;
double? doubleValue = obj as double?;

And once you have double?, you can directly cast it to decimal? and 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?);

Apart from being clear, this approach is also likely going to be pretty efficient.

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 a cast:

object obj = ...;
double? doubleValue = (double?)obj;

And once you have double?, you can 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?)(double?)obj;

Apart from being clear, this approach is also likely going to be pretty efficient.

Source Link
svick
  • 24.3k
  • 4
  • 52
  • 89

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:

object obj = ...;
double? doubleValue = obj as double?;

And once you have double?, you can directly cast it to decimal? and 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?);

Apart from being clear, this approach is also likely going to be pretty efficient.