Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 322
Boris Callens Avatar asked Sep 17 '08 14:09

Boris Callens


People also ask

Is null shortcut C#?

The null-coalescing operator ( ?? ) is like a shorthand, inline if/else statement that handles null values. This operator evaluates a reference value and, when found non-null, returns that value. When that reference is null , then the operator returns another, default value instead.

Does HasValue check for null?

The compiler replaces null comparisons with a call to HasValue , so there is no real difference. Just do whichever is more readable/makes more sense to you and your colleagues.

What is nullable type in C sharp?

C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values. For example, you can store any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable<Int32> variable. Similarly, you can assign true, false, or null in a Nullable<bool> variable.

What is the use of HasValue in C#?

HasValue indicates whether an instance of a nullable value type has a value of its underlying type. Nullable<T>. Value gets the value of an underlying type if HasValue is true . If HasValue is false , the Value property throws an InvalidOperationException.


2 Answers

aNullableDouble = double.TryParse(aString, out aDouble) ? (double?)aDouble : null;
like image 52
ljs Avatar answered Oct 18 '22 07:10

ljs


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;
}
like image 7
Joel Martinez Avatar answered Oct 18 '22 06:10

Joel Martinez