简体   繁体   中英

Shorthand if + nullable types (C#)

The following returns

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

aNullableDouble = (double.TryParse(aString, out aDouble) ? aDouble : null)

The reason why I can't just use aNullableBool instead of the roundtrip with aDouble is because aNullableDouble is a property of a generated EntityFramework class which cannot be used as an out par.

aNullableDouble = double.TryParse(aString, out aDouble) ? (double?)aDouble : null;

Just blow the syntax out into the full syntax instead of the shorthand ... it'll be easier to read:

aNullableDouble = null;
if (double.TryParse(aString, out aDouble))
{
    aNullableDouble = aDouble;
}
aNullableDouble = (double.TryParse(aString, out aDouble)?new Nullable<double>(aDouble):null)

The interesting side-effect of using nullable types is that you can't really use a shorthand IF. Shorthand IF has to return the same Type from both conditions, and it can't be null in either case. So, cast or write it out :)

.NET supports nullable types , but by declaring them as such you have to treat them a bit differently (as, understandably, something which is normally a value type now is sort of reference-ish).

This also might not help much if you end up having to do too much converting between nullable doubles and regular doubles... as might easily be the case with an auto-generated set of classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM