Nullable Types are introduced in C#2.0, they allow you to assign null to a value type variable. In C#, You cannot assign null to a value type variable, if you write something like this i.e int x = null , then this will give compile time error. However, You can declare a value type as Nullable Type and then assign null value.

Before going through in details, it is important to know Reference types and Value Types. If you haven’t gone through my previous article on Reference type and Value type then, please go through here.

Syntax & Usage ?

You can declare nullable type using Nullable<T> where T is a type,  for example.

We can also declare nullable type using question mark (?) operator as follows.

Example Here in below example, we have declared a variable as int i = 0 . Now if you write int i = null then compiler throws error as shown below.

Nullable Type
Figure – 1 – Declaration Type Exception

We can declare above value type as Nullable and assign null value at run time.

In below example code, we have declared a Nullable of type int and assigned null value at run-time.

Nullable Type Declaration
Figure – 2 – Type Declaration

Nullable types are mostly applicable to value types, you can’t declare a reference type as Nullable , because by default reference types supports null value. In below example System.String is a reference type so compiler throws error.

Nullable Type Declaration Exception
Figure – 3 –  Declaration Exception

Conversion of Nullable Type :

C# allows to perform conversions and casts on Nullable types.  Here in below, implicit conversion from non-nullable Int32 to Nullable<Int32> .

Similarly in below example, explicit conversion Nullable<Int32>  to non-nullable Int32 .

HasValue() property of Nullable Type :

The Nullable types are instances of System.Nullable<T> struct. It has a property as HasValue . It returns True, if the variable contains a value and returns False if it’s null.

Output :

Nullable Type Output
Figure – 4 –  Output

Where to use Nullable Type ?

Lets say you have a boolean field in your database and that also accept null value along with True/False  In that case you can define a Nullable of type bool and pass the null value as desired.

Important Points to be noted :

Below are some important points.

  • Nullable types can only be used with value types.
  • The HasValue property of Nullable type returns True, if the variable contains a value and returns False if it’s null.
  • Nullable<T> object returns type T instead of Nullable<T>. In below sample code, we have defined a nullable type and fetching the type information at runtime using GetType() method. When you run below program then, it will print System.Boolean instead of Nullable<Boolean>

Thanks for your time 🙂 feel free to provide your feedback and do check my other blogs on Dynamic type , Var type , Anonymous type and Reference Type and Value type .