views:

183

answers:

5

Hello,

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?

+3  A: 

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

krdluzni
+1  A: 

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.

routeNpingme
Typo. Suttle = subtle.
Andy_Vulhop
+1  A: 

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

TWith2Sugars
+2  A: 

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.

Edo
+9  A: 

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
Dan Diplo
Great! That makes sense. Thanks a lot :))
Valerie