Valerie
Valerie

Reputation: 229

Nullable variable types - .value member

I was wondering - when would I want to use the .Value member on a nullable type instead of just calling the variable itself?

e.g..

bool? b = true;

why would i use b.Value to get the value instead of just using b? What advantage or function does the .Value call add?

Upvotes: 7

Views: 696

Answers (5)

Brandon
Brandon

Reputation: 14196

The only difference is that they are 2 different types. If you have a bool? then it's a nullable type of bool.

If you call b.Value you're actually returning a bool and not a bool?.

Subtle, but when you need the non-nullable version of the object, use the .Value property.

Upvotes: 1

Dan Diplo
Dan Diplo

Reputation: 25359

The value property is read only and will return the actual value type. The value property can never be null.

If you expect to have a nullable return a value then check .HasValue and then reference Value. For instance, if you want to assign the value of a Nullable to an ordinary bool then you have to reference it's value:

bool? nullableBool = null;

if (nullableBool.HasValue)
{
    bool realBool = nullableBool.Value;
}

However, the following won't compile:

bool? nullableBool = true;
bool realBool = nullableBool; // Won't work

Upvotes: 13

Edo
Edo

Reputation: 1841

When you want to use methods / properties of the underlying type. Doesn't really apply to bool. Let me illustrate with DateTime:

DateTime? d;
int month = d.Value.Month;

You cannot access Month property directly from d, because DateTime? doesn't have this property.

Upvotes: 2

TWith2Sugars
TWith2Sugars

Reputation: 3434

For me it's not so much value as the is the property "HasValue" that I find useful

Upvotes: 1

krdluzni
krdluzni

Reputation: 797

.Value returns a bool rather than a bool? which will allow you to use it as a parameter to functions that don't expect nullable types.

Upvotes: 3

Related Questions