Nullable & Non-Nullable Types

Oxygene allows to explicitly specify the nullability of values such as variables, fields, properties or method parameters. For brevity, we'll use the term "variables" throughout this topic to refer to all four kinds of references.

Nullable variables may either contain a valid value or they may not — in the latter case they are considered to be nil. Non-nullable variables must always contain a value and cannot be nil.

In Oxygene (as in C# and Java), the default nullability of a variable is determined by its type. For value types (records, enums and simple numeric types), variables are assumed to be non-nullable by default, and always have a value (which might be 0, which is of course distinct from nil). By contrast, reference types (i.e. classes or interfaces) are considered nullable by default, and may be nil.

Nullability of a type can be expressed by explicitly prefixing the type name with a modifier. A variable can be made explicitly nullable with the nullable keyword, or explicitly non-nullable with the not nullable keyword combination.

For example:

var i1: Int32;                               // non-nullable by default
var b1: Button;                              // nullable by default

var i2: nullable Int32;                      // nullable
var b2: not nullable Button := new Button(); // not nullable, thus needs initialization

It is perfectly acceptable (and in many cases recommended) to apply what might appear to be redundant explicit nullability information, as it can help both the compiler and the user of APIs to understand the intention of the code.

For example, even though Strings are reference types, and nullable by default, marking a Method Parameter or a Method Result as nullable String can express the intention that the method will accept or potentially return a nil value.

Especially when working on platforms where much of the core libraries do currently not express this kind of information, and APIs refer to plain reference types without indication whether nil values are acceptable or to be expected, this extra information can help make your own APIs more robust and self-describing.

You can read more about this topic in more depth in the Nullability topic in the Language Concepts section.

See Also