Nullable types were integrated to the .NET framework 2.0 and have the main characteristic of encapsulate a value type in a System.Nullable structure, with a default null value while the object has not been initializated yet. The value ranges for numeric types for example will remain the same.
Sometimes nullable types can be very useful and they can really make coding easier and accurate. Imagine a column in a table that stores a flag and the column accepts null value.
You may in your application declare a nullable of Boolean that stores the value from that column. If the column has a null value, your variable will have a null value as well. You don’t need to assume default values for your variable what may in some cases store fake data.
1. Declare a nullable type
There are two different syntaxes to declare a nullable type:
2. Check if a nullable type has a value
To check if a nullable type has a value, the read-only property HasValue will help you to achieve that.
// Do something
3. Retrieve the nullable type value
To retrieve the value you may use the Value property or one of the GetValueOrDefault method overloads. The Value property should be used in conjunction with the HasValue property to ensure that your code will try to access the value only if there is a value.
4. Assign a nullable type to a non-nullable type
When you assign a nullable type to a non-nullable type you need to ensure that a value will be always assigned, forcing you to set a default value with the ?? operator as demonstrated on the following code:
bool myBool = myNullBoolean ?? false;