1

I have a nullable double

MyNullableDouble = MyDouble == 0 ? null : MyDouble;

This is causing me an issue :

Type of conditional expression cannot be determined because there is no implicit conversion between '' and 'double'

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
sprocket12
  • 5,368
  • 18
  • 64
  • 133

3 Answers3

5

you should cast Mydouble, otherwise on the left side you have type double? while in the right part you have double, so types are not equivalent (and that's exactly what the exception is saying):

MyNullableDouble = MyDouble == 0 ? null : (double?)MyDouble;
Tobia Zambon
  • 7,479
  • 3
  • 37
  • 69
  • Yes because double can be implicitly casted to nullableDouble, but the tertiary operator works in a different manner, there are lot of questions about this: see [this one](http://stackoverflow.com/questions/8155618/implicit-conversion-issue-in-a-ternary-condition) for example, and follow the various duplicated questions – Tobia Zambon Jul 31 '13 at 09:43
  • ok sorry I would have searched but I didnt know at the time it would be that kind of issue. – sprocket12 Jul 31 '13 at 09:44
0

yes,you cannot do like this ,both the value should be of same data type.Any specific reason to use tertiary..use if else ...

0

You can implement a generic approach to handle such situations. Since all Nullable types have GetValueOrDefault method, you can write an opposite method for non-Nullable structures:

    public static T? GetNullIfDefault<T>(this T value)
        where T: struct
    {
        if( value.Equals(default(T)))
        {
            return null;
        }

        return value;
    }

Example of usage:

MyNullableDouble = MyDouble.GetNullIfDefault();
Egor4eg
  • 2,678
  • 1
  • 22
  • 41