Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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

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.

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top