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?
If you want to use the default value of the underlying value type in place of null , use the Nullable<T>. GetValueOrDefault() method. At run time, if the value of a nullable value type is null , the explicit cast throws an InvalidOperationException.
You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.
HasValue: This property returns a bool value based on that if the Nullable variable has some value or not. If the variable has some value, then it will return true; otherwise, it will return false if it doesn't have value or it's null.
Empty(A constant for empty strings). This method will take a parameter that will be of System. String type. The method will return a Boolean value, like n case if the argument String type has null or empty string (“”), then it will return True value else it will return False value.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With