Is it safe to rewrite the following code:
bool b = foo.bar.HasValue ? foo.bar.Value : false;
to
bool b = foo.bar.Value ?? false;
where bar
is the nullable type bool?
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.
The conditional logical AND operator && , also known as the "short-circuiting" logical AND operator, computes the logical AND of its operands. The result of x && y is true if both x and y evaluate to true .
The unary postfix ! operator is the null-forgiving, or null-suppression, operator. In an enabled nullable annotation context, you use the null-forgiving operator to declare that expression x of a reference type isn't null : x! . The unary prefix ! operator is the logical negation operator.
The is operator checks if the result of an expression is compatible with a given type. For information about the type-testing is operator, see the is operator section of the Type-testing and cast operators article.
The easiest fix there is
bool b = foo.bar.GetValueOrDefault();
which is also actually cheaper than .Value
as it omits the has-value check. It will default to default(T)
, which is indeed false
here (it just returns the value of the underlying T
field, without any checks at all).
If you need a different default to default(T)
, then:
var value = yourNullable.GetValueOrDefault(yourPreferredValue);
What you want is:
bool b = foo.bar ?? false;
This is (surprisingly) safe and an intended use for the null-coalescing operator.
The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.
Source: http://msdn.microsoft.com/en-us/library/ms173224.aspx
In the case of Nullable<T>
, it is functionally equivalent to Nullable<T>.GetValueOrDefault(T defaultValue)
.
The code:
bool b = foo.bar.Value ?? false;
Will cause a compiler-error, because you cannot apply the operator to value types, and Nullable<T>.Value
always returns a value-type (or throws an exception when there is no value).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With