Nullable Types

Nullable Types

The null value is useful for initializing reference types, but null is itself a reference, and we cannot assign it to a value type. The following statement is therefore illegal in C#:-

int i = null; // illegal

However, C# defines a modifer that we can use to declare that a variable is a nullable value type. A nullable value type behaves in a similar manner to the original value type, but we can assign the null value to it. We use the question mark (?) to indicate that a value type is nullable, like this:-

int? i = null; // legal
Ebook Download
View all
Learn
View all