Member-only story

Nullable Types in C#

Shahzad Aslam
3 min readJul 17, 2024

--

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.

Nullable Types in C#

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.

--

--

Shahzad Aslam
Shahzad Aslam

Written by Shahzad Aslam

Welcome to c-sharptutorial.com. I am Shahzad Aslam. I am the founder of c-sharptutorial.com. I'm currently living near Islamabad, Pakistan.

No responses yet