Nullable Types in C#
I just read about
nullable types in C# 2.0 and was quite surprised how similar it is to Eek's syntax. In C# you write
int? a = 1;
and in Eek you write
int a? = 1
to define an nullable variable 'a' with a default value of 1. Eek's implementation will be different though. C# differentiates between value types (like int) and reference types, and in C# 1.0 only reference types could be null. That's why they added the extra feature for value types (which is actually just
a short notation for a wrapper class). In Eek everything is an object, there are no value types, all variables are references, and references are not nullable unless the question mark '?' modifier is used.
An interesting feature in C#'s syntax is the '??' operator. The statement
int x = a ?? 1;
takes 'a' if 'a' is not null, and 1 otherwise. This is an nice short cut, and I wonder whether I should provide something like this. Right now Eek's specs contain only two ways of eliminating nulls. Either the 'if/then/else' operator
int x = if a then a else 1
that allows default values, or the 'any' conversion
int x = any(a)
, which will fail at runtime if 'a' is null.
I am a little bit concerned about the number of Eek's operators. I want to keep the number as low as possible, to avoid Perl's line noise effects that occur when people are exposed to operators that they have never seen before. Right now Eek has all operators that Java has except the post- and pre- increment and decrement operators ('++' and '--'). The ternary operator 'x ? y : z' will be replaced by 'if x then y else z', because '?' and ':' are used for too many other things and this syntax allows several 'if's with a single 'else'. Additionally Eek has '..' and '.@' for accessing node descandants and attributes in XML trees, and the filter operator '.()'. These three are taken from
E4X. And Eek has several extra literals, especially '{someblock}' for closures and 'prefix:name' for XML QNames could have a line-noise effect. So I would really hate to add another operator. On the other hand, I expect null-elemination to be needed frequently.
9 hours later...
I think I found a solution: I use the '||' operator. This isn't too far from the original behaviour of '||', because every nullable reference in Eek is implictly convertible to bool anyway. If right-hand operand is a non-nullable reference other than bool, the left hand operator will be returned if it is not null and otherwise the right-hand operator. Without the modification it would be forbidden to use any non-nullable right hand operand except bool (and with bool it does not make any difference). Both operands must be compatible with the expected value for the expression, if there is one.
With the modified '||' operator the example can be written as
int x = a || 1
.
Two days later...
Ok, bad idea. The precedence of '||' is too low to be usable without parentheses.
written at 12:42. (0 Comments, Permalink)