Author : MD TAREQ HASSAN | Updated : 2021/03/22
What is Nullable Type?
- For value types (i.e. int), by default
null
cannot be used - Nullable type is a special feature of C# that allows
null
value to be assigned to a value type - A nullable value type
T?
represents all values of its underlying value typeT
and an additionalnull
valuebool x
:x
can have onlytrue
orfalse
bool? x
:x
can havetrue
,false
, ornull
- Any nullable value type is an instance of the generic
System.Nullable<T>
structure Nullable<T>
andT?
are interchangeable
Nullable Value Type
// Nullable types are VALUE types that can take null as value. The default value of a nullable type is null.
int? x = null; // no value
char? letter = 'a';
bool? flag = null;
// An array of a nullable value type:
int?[] arr = new int?[10];
Nullable Value Type to Normal Value Type
- Use null-coalescing operator
??
- Or use
Nullable<T>.GetValueOrDefault(T)
int? x = 10;
int foo = x ?? -1;
Console.WriteLine($"foo is {foo}"); // output: foo is 10
x = null;
int bar = x ?? -1;
Console.WriteLine($"bar is {bar}"); // output: bar is -1
Nullable Reference Type
- Reference types can have
null
as value by default - If reference type gets null value, there might be null reference exception
- C# 8.0 introduces the nullable reference types feature
- Nullable reference types aren’t new class types, but rather annotations on existing reference types. The compiler uses those annotations to help you find potential null reference errors in your code
- There’s no runtime difference between a non-nullable reference type and a nullable reference type
- Details: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-reference-types
HasValue and Value
- Read-only properties to examine and get a value of a nullable value type variable
Nullable<T>.HasValue
: indicates whether an instance of a nullable value type has a value of its underlying typeNullable<T>.Value
: gets the value of an underlying type ifHasValue
istrue
. IfHasValue
isfalse
, the Value property throws anInvalidOperationException
- For Nullable Reference Type i.e.
string?
orT?
- does not have “
.HasValue
” & “.Value
” because nullable reference types aren’t new class types - just for compiler to help you find potential null reference errors in your code
- does not have “
For “string? x
”, you might need to use “string.IsNullOrEmpty(x)
”