Member-only story
Nullable Types in C#
In C#, nullable types are a feature introduced to allow value types (such as int, double, bool, etc.) to have a value of null, in addition to their normal range of values. This is particularly useful in scenarios where you need to represent the absence of a value or where a value might legitimately be undefined.
1. Declaration and assignment
You can declare and assign a value to a data type (double, char, int, bool) or you can also declare and assign a null value to vairable in C# 2.0.
Example
double? pi = 3.14;
char? letter = 'a';
int m2 = 10;
int? m = m2;
bool? flag = null;
// An array of a nullable value type:
int?[] arr = new int?[10];
2. Check Nullable Value Type
You can use is operator to check both a vairable of datatype is nullable or not and retireveing a value of an mentioned type.
Example
int? a = 42;
if (a is int valueOfA)
{
Console.WriteLine($"a = {valueOfA}");
}
else
{
Console.WriteLine("a does not have a value");
}
// Output:
// a = 42
3. Check Nullable Type With HasValue Property:
You can check a vairable of mentioned data type has null value or not with HasValue property.