Nullable Type and Null Coalescing Operator in C#

Introduction

This article explains the basics of nullable types and the coalescing operator for C# for beginners. Handing null in C# can be very confusing for developers. Basically it provides a way to assign null to value types in C# code. Nullable types work as a connector between a database and C# code to provide a way to transform the nulls to be used in C# code.

Null Coalescing operators simplify the way to check for nulls and shorten the C# code when the developer is dealing with nulls.

Nullable types

Nullable types are a kind of value type variable in C# to which null values can be assigned.

C# has categorized Types broadly into the two types Value types and reference types as in the following:

  • Value Types: int , float , double, datetime
  • Reference Types: Classes, arrays, delegates and so on

The default value of a reference type is null but for values type it holds some kind of value meaning by default value types are non nullable so whenever we use a value type the default value should be provided for those types.

Example below

Int i=0
Bool isPresent=true
Float j=0

Nullable Type

In the above it can be seen that the compiler message says that null is being assigned to the int data type.

The answer to this problem is for the value type to be a nullable type.

Nullable types are instances of the System.Nullable<T> struct.

For example if we use Nullable<Int32> then we can assign any value from -2147483648 to 2147483647 as per int and we can assign the null value.

To make a non nullable value type nullable ? is being used.

int i=0 (null not possible): non nullable type
int ? i=null (Null possible): nullable type

Why Nullable types, still confused

Alright consider a sample requirement of a web form that is a user addition for a new employee in an organization.

Here we have a number of fields for including name, age and so on where Name, age is mandatory field and Ex-employee is a non-mandatory field, meaning the user can choose to not enter a value for this when entering the detail so null could be one of the answers.

Sample code
  1.  namespace nullableTypes   
  2. {   
  3.     class Program   
  4.     {   
  5.         static void Main(string[] args)   
  6.         {   
  7.             string s = null;   
  8.             //int=null;   
  9.             bool? exEmployee = null;   
  10.             if (exEmployee == true)   
  11.             {   
  12.                 Console.WriteLine("User is an ex employee of orgainization!!!!");   
  13.             }   
  14.             else if (exEmployee == false)   
  15.             {   
  16.                 Console.WriteLine("User is not an ex employee of orgainization!!!!");   
  17.             }   
  18.             else   
  19.             {   
  20.                 Console.WriteLine("User has not entered the required detail!!!!");   
  21.             }   
  22.             Console.ReadLine();   
  23.         }   
  24.     }   

C# Code has a value type and a reference type but database data types do not.

So wherever the developer works with C# and a database they need a way to deal with null values stored in the database that are later retrieved by C# code for further processing.

Here nullable types work as a connector between a database and C# code to provide a way to transform the nulls to be used in C# code.

Important sticky

  • Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type.
  • A Nullable Type is a struct type that holds a value type (struct) and a Boolean flag, named HasValue to indicate whether the value is null or not.
  • Nested nullable types are not allowed. The following line will not compile: Nullable<Nullable<int>> n;
  • Nullable<t> itself is a value type, it is fairly lightweight.

Null Coalescing Operator (??)

The ?? Operator is called the null-coalescing operator.

It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand, in other words we can say the Null Coalescing Operator (??) is a binary operator for checking for null values. It can be used with both nullable types and reference types. It is represented as i ?? j which means if i is non-null then evaluate it to i, otherwise J.

Null Coalescing Operator

Here there is not an implicit conversion of a nullable type into a non nullable type. So the explicit convention should be necessary to compile the code.
 
compile the code

.value is returning here int type

Here discountedItems = _discountedItem.value;

Sample Code
  1. namespace nullableTypes       
  2.    class Program   
  3.    {   
  4.        static void Main(string[] args)   
  5.        {   
  6.            int? _discountedItem = 10;   
  7.            int discountedItems;       
  8.            if (_discountedItem == null)   
  9.            {   
  10.                discountedItems = 0;   
  11.            }   
  12.            else   
  13.            {   
  14.                discountedItems = _discountedItem.Value;   
  15.            }   
  16.           Console.WriteLine("No Of discounted Items are :" + discountedItems);   
  17.            //   using coalescing  operator (??)   
  18.            int discountedItem = _discountedItem ?? 0;   
  19.            Console.WriteLine("No Of discounted Items are : (with coalescing ) " + discountedItems);   
  20.            Console.ReadLine();   
  21.        }   
  22.    } 

Above I am trying to explain the Null Coalescing Operator (??) to shorten the code.