Non-Nullable Types

Similar to how value types can be made nullable in standard Visual Basic by suffixing the typename with a question mark (?), Mercury allows reference types – which are nullable by default – to be marked as not nullable by suffixing the type name with an exclamation point (!).

This can make for more robust code, as variables, fields, properties or parameters declared as such can be relied on to not be Nothing or Null. In many cases, the compiler can even emit compile-time warnings or errors, for example when passing a literal Null or Nothing to a non-nullable parameter.

For consistency, the ! operator is alos allowed on value types, where it will be ignored, simliar to how the ? is allowed on referene types (are nullable by default) and is ignored there.

Dim i1 As Int32                        ' non-nullable by default, 0
Dim b1 As Button                       ' nullable by default, null

Dim i2 As Int32!                       ' non-nullable by default, 0, same as above
Dim b1 As Button?                      ' nullable by default, null, same as above

Dim i2 As Int32?                       ' nullable, null
Dim b2 As Button! = new Button();      ' not nullable, thus needs initialization

Please also refer to the Nullability topic in the Language Concepts section for more detailed coverage.

See Also