In this article we will learn about the,
- Nullable Types in C#
- Null coalescing Operator??
Nullable Type
C# provides us a data type, called Nullable type, so according to this if we assign any variable with nullable type then we can assign normal range value as well as Null value to variable.
In C# there are 2 type of categories,
- Value type – int double,float,enum , struct etc.
- Reference type – interface, class , delegated,array, etc
Deceleration of a nullable type is,
- < data_type> ? <variable_name> = null;
By default value type variable are non nullable , for making them nullable we use “?” nullable type. For ex int i = 0 ( here i is non nullable, so we can not assign null to i, i = null will give a compiler error)
At second place we write that
int? i = 0 (i is nullable int, so i=null is legal and it will not give ant compiler error)
Nullable types is just like a bridge b/w the C# type and database types
Following example show the nullable type in C#,
- using System;
-
- using System.Collections.Generic;
-
- using System.Linq;
-
- using System.Web;
-
- namespace NullableType
-
- {
-
- class NullableTypeInCSharp
-
- {
-
- static void Main(string[] args)
-
- {
-
- int? Number1 = null;
-
- int? Number2 = 45;
-
- double? Number3 = new double?();
-
- double? Number4 = 31;
-
- bool? lbnValue = new bool?();
-
-
-
- Console.WriteLine("Nullables perameters: {0}, {1}, {2}, {3}", Number1, Number2, Number3, Number4);
-
- Console.WriteLine("A C# Nullable boolean value: {0}", lbnValue);
-
- Console.ReadLine();
-
- }
-
- }
-
- }
The Null Coalescing Operator (??)
Null coalescing operator(??) is used with the nullable type variable and reference type variable.
Basically it is used for converting an operand to another nullable value type operand ,here an implicit conversion is possible.
Use of this coalescing operator (??) is that If the assign value of the operand is null then operator return the value of 2nd operand, otherwise it return 1st operand value.
Following example is shown the coalescing operator,
- using System;
-
- using System.Collections.Generic;
-
- using System.Linq;
-
- using System.Web;
-
- namespace CoalescingTypeInCSharp
-
- {
-
- class CoalescingType
-
- {
-
- static void Main(string[] args)
-
- {
-
- double? number1 = null;
-
- double? number2 = 4.12;
-
- double Number3;
-
- Number3 = number1 ?? 6.12;
-
- Console.WriteLine(" Value of Number3: {0}", Number3);
-
- Number3 = number2 ?? 5.34;
-
- Console.WriteLine(" Value of Number3: {0}", Number3);
-
- Console.ReadLine();
-
- }
-
- }
-
- }