Nullable Ain’t Nothin’
By Bob Studer, Senior Synergy/DE Developer
Synergy/DE 10.1 offers improved support for nullable types. This article will explain what nullable types are and how to use them.
With variables of value types, there is typically no way to tell that a value is undefined, or not set. If you have a Boolean variable, for example, it can either be true or false. But if you haven’t set it yet, it is set to false anyway — and there’s no way to tell the difference. At this point, you may want a three-state Boolean: true, false, and ^NULL, and that’s where nullable types become useful. If “undefined” is valid for a data field that’s a value type, a nullable type allows it without having to reserve one of the valid values of the type to mean “undefined.”
That’s the function of nullable types: They essentially add ^NULL to the possible values that a value type can assume. A nullable int, for example, can contain the values -2147483648 to 2147483647 and ^NULL. (Prior to version 10.1, you would have had to, in many cases, use the Value and HasValue properties of the variable to check this.)
A nullable type can be made from any CLS value type. In Synergy DBL on .NET, you can declare a nullable type in one of two ways: as a generic type or by appending a question mark (?) to the end of the value type. For example,
record nbval, Nullable<boolean> nival, int?
Nullable variables can be set just like any other value type. They can also be set to ^NULL, which sets them back to the null state:
nbval = true nival = ^NULL
You can test to see if a nullable variable is undefined by comparing it with ^NULL:
if (nival == ^NULL) console.writeline(“nival is not set”)
You can also assign a nullable type to a non-nullable field of the same base type:
data isRead, Boolean? data state, Boolean isRead = true state = isRead
If the nullable type is in its null state, the assignment will result in the value type field being set to the default value for the type, which in the case of Boolean is false.
The subroutine below takes a nullable Boolean as an argument, and a string to use as a name will print out the current state of the argument passed in.
subroutine WriteState arg, boolean? name, string proc console.write(name) if (arg == ^NULL) then console.writeline(" is ^NULL") else if (arg) then console.writeline(" is true") else console.writeline(" is false") end
In the first IF statement, if arg is ^NULL, that fact is written out. Otherwise, if the value of arg is true, the statement that writes “ is true” is executed; if not, it’s reported to be false.
So now you can tell the difference!
For more information, see “Nullable types” in the Synergy/DE documentation.
See Synergy/DE 10.1 for more information.