Introduction
A nullable type variable use to a
hold null value, which provide the c# language. You can not assign a null
value directly to a int type. So to make the value type accept a null
value, nullable types are used. You cannot create a nullable type based on a
reference type because reference types already support the
null value.
Example
using
System;
namespace
null_coalescing_operator_in_c_sharp
{
class
Program
{
static
void Main(string[]
args)
{
//define nullable
type variable, which value is define null
int? number =
null;
// is the hasvalue
property which return true or false
try
{
Console.WriteLine(number.Value);
//for true
}
catch(System.InvalidOperationException
e)
{
Console.WriteLine(e.Message);
}
// if we have provide
default value to null able type variable through
GetValueOrDefault() function
number = number.GetValueOrDefault();
//then
try
{
Console.WriteLine("\nGet
Default Value: {0}", number.Value);
//for true
}
catch(System.InvalidOperationException
e)
{
Console.WriteLine(e.Message);
}
// if we have
provide a value to nullable type variable through user
number = 10;
//then
try
{
Console.WriteLine("\nGet
User Value : {0}", number.Value);
//for true
}
catch(System.InvalidOperationException
e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
}
Output