Nullable Types And Null Coalescing Operator In C#

Nullable Types and Null Coalescing Operator in C#
 
This is a fundamental concept in C# programming. Here I am going to explain what is nullable type, what is the null coalescing operator in C#, and how we can use this operator in LINQ.

The data types in C# are divided into two main categories: Value Type and Reference Type.
 
Value type variable cannot be null, but in reference type variable we can assign null value.

Let us check what will happen when we assign null to a value type.

 
So when I am trying to assign null value to an integer it is showing the following error: "Cannot Convert null to 'Int'.because it is a non-nullable value type." 
 
This is a common type of error we usually face while coding. There are two ways to solve this problem.  
  •  Nullable<int> x = null;
  •   int ? x = null;

    The above shown two ways can convert a  non-nullable value type to nullable value type in C#.

    From this we conclude that:

    A type is said to be nullable if it can be assigned a value or can be assigned null, which means the type has no value whatsoever. By default, all reference types, such as string, are nullable, but all value types, such as Int32, are not.

  • There are two members of nullable type.

    1: HasValue: HasValue is of type bool. It is set to true when the variable contains a non-null value.

    1. static void Main(string[] args)  
    2. {  
    3.  int? x = 5;  
    4.  if(x.HasValue)  
    5.   {  
    6.     Console.WriteLine("contain not nullable value.");  
    7.   }  
    8.  else  
    9.   {  
    10.     Console.WriteLine("contain Null value.");  
    11.   }  
    12.     Console.ReadLine();  
    13. }  
    So the output will contain non-nullable value.

    2.Value: Value is of Boolean type. It contains the data stored in the nullable type.
    1. static void Main(string[] args)  
    2. {  
    3. int? x = 5;  
    4. if(x.HasValue)  
    5. {  
    6. Console.WriteLine(x.Value.ToString());  
    7. }  
    8. else  
    9. {  
    10. Console.WriteLine("contain Null value.");  
    11. }  
    12. Console.ReadLine();  
    Here the output will be -5.

    This is all about Nullable types in C#. Now here I am going to discuss what is Null Coalescing operator in C#.
  • Null-Collation: Null-collation(??) is an important operator in c#. As per MSDN definition:

    The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand. The C# Null Coalescing Operator (??)  is a binary operator that simplifies checking for null values. It is used to assign a default value to a variable when the value is null.

    1. class Program  
    2.     {  
    3.         static void Main(string[] args)  
    4.         {  
    5.             string name = null;  
    6.             string myname = name ?? "Laxmi";  
    7.             Console.WriteLine(myname);  
    8.             Console.ReadLine();  
    9.         }  
    10.     }  


    The output here is Laxmi. This is because the variable name is null and the null Coalescing operator check for null value. If it is null then it will assign the default value. 
  • In property also we can use null Coalescing operator like this.

    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5. using System.Threading.Tasks;  
    6.   
    7. namespace NullCollation  
    8. {  
    9.     class employee  
    10.     {  
    11.           
    12.     }  
    13.     class Program  
    14.     {  
    15.          
    16.         static string _name;  
    17.   
    18.         static string Name  
    19.         {  
    20.             get  
    21.             {  
    22.                 return _name ?? "Kailash";  
    23.             }  
    24.             set  
    25.             {  
    26.                 _name = value;  
    27.             }  
    28.         }  
    29.         public int age { getset; }  
    30.         static void Main(string[] args)  
    31.         {  
    32.              
    33.             Console.WriteLine(Name);  
    34.             Console.ReadLine();  
    35.         }  
    36.     }  
    37. }  

    Now I am showing you how this operator is used in LINQ.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace NullCollation  
  8. {  
  9.     public class Employee  
  10.     {  
  11.         public int Id { getset; }  
  12.         public int age { getset; }  
  13.         public string name { getset; }  
  14.         public string gender { getset; }  
  15.     }  
  16.     class Program  
  17.     {  
  18.   
  19.         static void Main(string[] args)  
  20.         {  
  21.             List<Employee> li = new List<Employee>();  
  22.             li.Add(new Employee { Id = 1, age = 19, name = "Ritesh", gender = "M" });  
  23.             li.Add(new Employee { Id = 2, age = 20, name = "sujit", gender = "M" });  
  24.             li.Add(new Employee { Id = 3, age = 23, name = "Kabir", gender = "F" });  
  25.             li.Add(new Employee { Id = 4, age = 3, name = null, gender = "F" });  
  26.             li.Add(new Employee { Id = 5, age = 24, name = "Kamlesh", gender = "M" });  
  27.             li.Add(new Employee { Id = 6, age = 28, name = "Manoj", gender = "M" });  
  28.   
  29.             var Data = from emp in li where emp.Id == 4 select new { Name = emp.name ?? "No name" };  
  30.   
  31.             foreach (var obj in Data)  
  32.             {  
  33.                 Console.WriteLine(obj.Name);  
  34.             }  
  35.             Console.ReadLine();  
  36.   
  37.         }  
  38.     }  
  39. }  


So in this way we can use null Coalescing operator in LINQ Queries.
 
Read more articles on LINQ: