Sunday, 11 January 2015

Nullable Types(?) and Null Coalescing Operator(??)

1.Nullable Types '?' : 

In C-sharp Types are divided into 2 categories

Value Types: Int, float, double, struct, enums etc
Reference Types: Interface, class, delegates, arrays etc

Nullable type is to provide null value to any type.

By Default value types are non-nullable to make them nullable use "?"

Exp:

int i = 0;              // i is non nullable because data type of i is int, so i cannot set to null .
int i = null;         // it will generate compiler error

so we use "?" to provide null value to 'i'

Syntax:
int? i = null;

Exp:
  1. {  
  2.      static void Main()  
  3.      {  
  4.           string name = null;  
  5.           int i= null;  
  6.           int? i = null;  
  7.      }  

In Line 4 we initialize name to null since it is legal because string is the reference type variable.
In Line 5 we initialize i to null it will generate a compiler error because i is Value type. So, we use "?" in line 6 to make it legal and nullable.


2.Null Coalescing Operator '??' :

This is used to define a default value for nullable types or reference type it return the left hand operand if the operand is not null otherwise it return the right hand operand.

Syntax:
              x=y??1;
Exp:

  1. class Test
  2. {
  3.    static void Main()
  4.    {
  5.       int availableTickets;
  6.       int? ticketOnSale = null;

  7.          if(ticketOnSale == null)
  8.          {
  9.             availableTickets = 0;  // Assign a value when it satisfy null condition

  10.          }

  11.          else
  12.          {
  13.             availableTickets = (int)ticketOnSale;
             }

  14.          Console.WriteLine(availableTickets);
       }


OR
  1. class Test
  2. {
  3.    static void Main()
  4.    {
  5.       int availableTickets;
  6.       int? ticketOnSale = null;

  7.        availableTickets = ticketOnSale??0;      // null-coalescing operator              

  8.       Console.WriteLine(availableTickets);
       }