The value datatypes, which we have learned so far, cannot be assigned a NULL value.

For example, you can declare:

int a=10;

and the following code will throw an error:

int a= null;

In C# 2.0, a special datatypes known as nullable was introduced. This allows you to assign null to value type variables. 

Syntax

datatype ? variable_name = value | null;

Example

int? a = null;
float? b = null;

Characteristics of nullable type

  • The HasValue property returns true if the variable has a value.
  • The Value property will throw an InvalidOperationException if the variable does not have a value.

Example

using System;
using System.IO;
namespace LearnCSharp
{
class Program
{
static void Main(string[] args)
{
int? a = null;
float? b = null;
Console.WriteLine(a);
Console.WriteLine(b);
if (a.HasValue)
Console.WriteLine("Variable a has a value");
else
Console.WriteLine("Variable a does not have a value");
Console.ReadKey();
}
}
}