Nullable Type and Null Coalescing Operator






3.60/5 (10 votes)
Nullable Type and Null Coalescing Operator
Introduction
We will learn two points in this tip:
- Nullable types in C#
- Null Coalescing operator in C#
Nullable Types in C#
There are two types of data types in C#:
- Value Types:
int
,float
,decimal
, etc. - References Types: Interfaces, Class, Delegates, Arrays, etc.
All value types are non nullable types in C#, make them nullable type use ?
operator.
int i = 3
is non nullableint? i null
is nullable
Point is why C# introduced nullable types.
- Nullable types are very helpful for optional fields. You don't get it. Wait for a moment, we understand it through an example.
Let us suppose we have 3 fields in a given example.
using System; namespace NullableType { class Program { static void Main(string[] args) { Console.WriteLine("Enter FN"); string firstName = Console.ReadLine(); Console.WriteLine("Enter LN"); string lastName = Console.ReadLine(); Console.WriteLine("Are you Minor(true/false)"); string minor = Console.ReadLine(); bool? areYouMinor = null; if (!string.IsNullOrEmpty(minor)) { areYouMinor = Convert.ToBoolean(minor); } Console.WriteLine("Output:\n______________"); Console.WriteLine("First Name:{0}",firstName); Console.WriteLine("Last Name:{0}", lastName); if (areYouMinor == true) { Console.WriteLine("Are You Minor : Yes"); } else if (areYouMinor == false) { Console.WriteLine("Are You Minor : No"); } else { Console.WriteLine("Are You Minor : Did not provide the value"); } Console.ReadLine(); } } }
In this example, if user does not provide the value for third field, then the output will be:
- Nullable types bridge between C# types and database types.
It means database does not have any value type or reference type, you can store
null
in any type in database.Counter part in Nullable type is
Null
Coalescing operator.
Null Coalescing Operator in C#
Null Coalescing operator is used when you have to assign some value if field has null
value.
You did'nt get it again, wait for a moment. We will try to understand it through an example.
using System;
namespace NullCoalescingOperator
{
class Program
{
static void Main(string[] args)
{
int? itemsOnSale = null;
int availableItems;
if (itemsOnSale == null)
{
availableItems = 0;
}
else
{
availableItems = (int)itemsOnSale;
}
Console.WriteLine("Available Items are {0}",availableItems);
Console.ReadLine();
}
}
}
In this example, if itemOnSale
field has null
value, then output will be:
Apart from that, we write the above example with the help of null
coalescing operator.
using System;
namespace NullCoalescingOperator
{
class Program
{
static void Main(string[] args)
{
int? itemsOnSale = null;
int availableItems = itemsOnSale ?? 0;
Console.WriteLine("Available Items are {0}",availableItems);
Console.ReadLine();
}
}
}
The output will be the same...
...but it makes our code neat and clean and this is the beauty of null
coalescing operator.