Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 235
Valerie Avatar asked Jul 29 '09 20:07

Valerie


People also ask

How do you access the underlying value of a nullable type?

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.

How do you declare a nullable variable in C#?

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.

Does HasValue check for null?

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.

How do you handle nullable values in C#?

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.


1 Answers

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
like image 73
Dan Diplo Avatar answered Sep 23 '22 02:09

Dan Diplo