Nullable variable types -.value member

I was wondering - when would I want to use the .Value member for a type with a null name instead of just calling this variable?

eg..

BOOL? b = true;

why should I use b.Value to get the value, and not just use b? What advantage or function does the .Value call invoke?

+7
c # types nullable member
source share
5 answers

The value property is read-only and returns the type of the actual value. The value property can never be null.

If you expect to return a value with a null value, check the .HasValue value and then the Value link. For example, if you want to set the Nullable value to a regular bool, you need to specify its value:

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

However, the following will not compile:

 bool? nullableBool = true; bool realBool = nullableBool; // Won't work 
+13
source share

.Value returns bool, not bool? which allows you to use it as a parameter for functions that do not expect types with a null value.

+3
source share

If you want to use methods / properties of the base type. This does not really apply to bool. Let me illustrate with DateTime :

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

You cannot access the Month property directly from d, because DateTime? does not have this property.

+2
source share

The only difference is that they are two different types. If you have a bool? then it is a bool type with a null value.

If you call b.Value , are you actually returning bool , not bool? .

Thin, but if you need a version with a null value, use the .Value property.

+1
source share

It's not as valuable to me as the "HasValue" property, which I find useful.

+1
source share

All Articles