This tutorial shows in a simple Cω program how to work with possibly-null values.
It is very convenient to be able to express in the type-system
that null is an expected value. In the CLR, member access throws a
NullReferenceException when the receiver is null. For
example, after the assignment Button b = null; subsequent
member access b.AllowDrop will fail. In many cases we
don't care what happens if the receiver is null (this
is the default in Objective C, where null behaves as
the zero element of member access), but in order to achieve that we need to
write a lot of boiler-plate code:
if(b!=null){
... do something with b ...
} else {
... performs some default action ... }
When the receiver has static type T? in
Cω, member access is lifted for the other stream types, and does nothing
except for propagating null. The possibility of failure
in recorded in the return type of the lifted member access, which becomes
bool? instead of bool.
Button? b = null; bool? d = b.AllowDrop; // returns null
For value types, T? does not introduce reference
identity, that is, values of type T? are still copied
on assignment; the important difference between value types T
and T? is that instances of T? can
be null whereas instances of value type T
are never null.
The following is a complete Cω program that demonstrates working with
possibly-null values.
using Microsoft.Comega;
using System.Windows.Forms;
public class Test {
static void Main() {
Button? b = null;
bool? d = b.AllowDrop;
//succeeds
Button c = (Button)b;
try {
bool e = (bool)d;
} catch(NullReferenceException e) {
Console.WriteLine("d == null = {0}", d == null);
}
Console.ReadLine();
}
}
d == null = True