Nullable Types

Added in .NET 2.0
Nullable types can only be used with value types.
Nullable types can represent all the values of an underlying type plus an additional null value.

System.Nullable<T> variable; 

T can be any value type, including struct
T cannot be a referenced type


Every nullable type has two public readonly properties
HasValue - false when variable contains a null value
Value - the value when variable does not contain a null value
Use value property to get the value of nullable type.
Use HasValue property to check whether value is assigned to nullable type or not.
You can only use == and != operators with a nullable type.



Shorthand Syntax

You can use the '?' operator to shorthand the syntax e.g. int?, long? instead of using Nullable<T>.

T? variable; 
int? myInteger = null;
double? myDouble = null;
System.DateTime? myDateTime = null;


Only Value Types

Nullable<T> and the ? suffix are for value types such as Int32, Double, DateTime, etc.
String is already a nullable type.



Null Coalescing operator - ??

Before this operator you had to use the conditional operator.
If "a" is null then (b = -1).
If "a" is not null then (b = a)

int? a = null; 
int? b = (a == null) ? -1 : a;
Console.WriteLine(b);

Alternatively you can use the '??' operator to assign a nullable type to a non-nullable type using slightly less code.

int? a = null; 
int? b = a ?? -1;
Console.WriteLine(b);


Boxing

Objects based on nullable types are only boxed when the object is not null.

bool? B = null; 
object o = b;
//o is null

bool? B = true;
object o = b;
//o is true

if (b == null)
{
}




© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext