Click here to Skip to main content
15,860,972 members
Articles / Programming Languages / C#
Tip/Trick

Nullable Type and Null Coalescing Operator in C#

Rate me:
Please Sign up or sign in to vote.
4.86/5 (4 votes)
25 Jun 2014CPOL3 min read 16.1K   7   3
This tip discusses the Nullable Type and Null Coalescing Operator in C#

Introduction

This tip explains the basics of nullable types and the coalescing operator for C# for beginners. Handling 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:

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

Image 1

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</t><t>.

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.

C#
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

C#
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.        }    
25.    }  

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<int><nullable<int>
  • 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.

Image 2

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.

Image 3

.value is returning here int type.

Here discountedItems = _discountedItem.value;

Sample Code

C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionplease correct HTML for: Nested nullable types Pin
Member 1070168327-Jun-14 1:26
professionalMember 1070168327-Jun-14 1:26 
QuestionGood Article. Pin
umlcat25-Jun-14 11:50
umlcat25-Jun-14 11:50 
AnswerRe: Good Article. Pin
Abhishek Geek25-Jun-14 18:21
professionalAbhishek Geek25-Jun-14 18:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.