freshbm
freshbm

Reputation: 5622

Check .HasValue and .Value for Nullabe of T

I've need to do some refactoring and I came across to this:

if(LoanTerms.RateIncreasable.HasValue && LoanTerms.RateIncreasable.Value) { ... }

and LoanTerms.RateIncreasable is of type System.Nullable<bool>

So I'm wondering do I need .HasValue check on this? Will null be treated like false in if statement?

Upvotes: 2

Views: 1233

Answers (2)

casillas
casillas

Reputation: 16793

The following code will handle your issue.

if(LoanTerms.RateIncreasable.GetValueOrDefault()) { ... }

If you call GetValueOrDefault it checks if HasValue is true or false:

public T GetValueOrDefault(T defaultValue)
{
    return HasValue ? value : defaultValue;
}

Upvotes: 1

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391276

Since the default of bool is false you can use this code which does everything you need:

if(LoanTerms.RateIncreasable.GetValueOrDefault()) { ... }

For more information, look at the documentation at MSDN: Nullable(T).GetValueOrDefault().

But to answer your question: It is not legal to read the Value property of Nullable<T> if the Nullable<T> value is null (ie. HasValue == false), you'll get an exception. So if you absolutely must read Value, ensure it has a value first.

Upvotes: 12

Related Questions