Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewrite HasValue to the ?? Operators

Tags:

c#

nullable

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?

like image 240
radbyx Avatar asked Jun 24 '11 11:06

radbyx


People also ask

What is HasValue?

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.

What does && mean in C#?

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 .

What is null forgiving operator?

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.

Is operator in C sharp?

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.


2 Answers

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);
like image 181
Marc Gravell Avatar answered Oct 26 '22 09:10

Marc Gravell


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

like image 40
Paul Turner Avatar answered Oct 26 '22 07:10

Paul Turner