Learn how to work with Nullable types in C#?

How to Work with Nullable Types in C#

In C# language, there are majorly two types of data types Value and Reference type. We can not assign a null value directly to the Value data type, therefore, C# 2.0 provides us the Nullable types to assign a value data type to null.

What is Nullable types?

As described above, the Nullable types used to assign the null value to the value data type. That means we can directly assign a null value to a value data type attribute. Using Nullable<T>, we can declare a null value where T is a type like int, float, bool, etc.
Nullable types represent the Null value along with the actual range of that data type. Like the int data type can hold the value from -2147483648 to 2147483647 but a Nullable int can hold the value null and range from -2147483648 to 2147483647

How to declare Nullable types?

There are two ways to declare Nullable types.
Nullable<int> example;
OR
int? Example;

Properties of Nullable types?

Nullable types have two properties.

  • HasValue
  • Value

HasValue: This property returns a value of bool depending on whether or not the nullable variable has a value. If the variable has a value, it returns true; otherwise, if it has no value or is null, it returns false.


Nullable<int> a = null;

Console.WriteLine(a.HasValue); // Print False

Nullable<int> b = 9;

Console.WriteLine(b.HasValue); // Print True

Value: The value of the variable Nullable form is given by this property. If the variable has any value, the value will be returned; else, it will give the runtime InvalidOperationException exception when the variable value is null.

Nullable<int> a = null;
Console.WriteLine(a.Value); // Gives run time exception of type ‘InvalidOperationException’
Nullable<int> b = 9;
Console.WriteLine(b.Value); // Print 9

You can read more about method of Nullable types and rules of using Nullable types in this blog here:
How to work with Nullable types in C#