Nullable types are instances of the System.Nullable<T> struct.
In C# 2.0 and above, you can store null value in any of your datatypes. But the datatype is little bit different.
We know that bool type will hold either true or false. But nullable bool will allow you to assign null also.
Characteristics:
Value Type
Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.)
Assign a value to a nullable type in the same way as for an ordinary value type, for example
int? i = 10;
double? d1 = 3.14;
bool? flag = null;
char? letter = 'a';
int?[] arr = new int?[10];
GetValueOrDefault
Use the System.Nullable.GetValueOrDefault property to return either the assigned value, or the default value for the underlying type if the value is null, for example
int x? = 10;
int j = x.GetValueOrDefault();
HasValue & Value
Use the HasValue and Value read-only properties to test for null and retrieve the value, for example
if (x.HasValue) j = x.Value;
The HasValue property returns true if the variable contains a value, or false if it is null.
The Value property returns a value if one is assigned, otherwise a System.InvalidOperationException is thrown.
The default value for a nullable type variable sets HasValue to false. The Value is undefined.
Conversions
Explicit Conversions:
A nullable type can be cast to a regular type, either explicitly with a cast, or by using the Value property. For example:
int? n = null;
//int m1 = n; // Will not compile.
int m2 = (int)n; // Compiles, but will create an exception if x is null.
int m3 = n.Value; // Compiles, but will create an exception if x is null.
Implicit Conversions:
The conversion from an ordinary type to a nullable type, is implicit.
int? n2;
n2 = 10; // Implicit conversion.
Operators
The predefined unary and binary operators and any user-defined operators that exist for value types may also be used by nullable types.
int? a = 10;
int? b = null;
a++; // Increment by 1, now a is 11.
Join the conversation! Your thoughts help the community grow.