Nullable Types

Maybe you’ve already tried it before, to declare an integer as null. But when building your application, you received the error message “Cannot convert null to ‘int’ because it is a non-nullable value type”. Nullable types are variables that can be assigned with the value ‘null’. Allmost all value types can be declared as a nullable type. To declare a value type as a nullable type, you have to add a questionmark after the type name. For example:

int? i = null;
double? d = null;
char? c = null;
bool? b = null;

Each nullable type has two read-only properties: HasValue and Value.
HasValue is a bool property. If the current value is ‘null’, HasValue will return false, otherwise it will return true. The HasValue property can be used to test if a variable contains a value.

Value property contains the meaningful value of the variable. Accessing Value when it’s declared as ‘null’ will throw a InvalidOperationException.

int? a = 10;
if (a.HasValue)
    Console.WriteLine("no value");

It’s possible to define a default value which is returned when a nullable type is assigned to a non-nullable type.

int? a = null;
int b = a ?? 10;

In this example b equals the value of a, unless a is null. In this case b will be 10.

Conversion from a nullable type to a non-nullable type.

A nullable type can be cast to a regular type, either explicitly with a cast, or by using the Value property. If the value is still ‘null’ when converting, it will throw a InvalidOperationException.

int? a = null;
int b = (int)a;
int c = a.Value;

Comments are closed.

%d bloggers like this: