Sunday, July 30, 2006

The CLR Nullable DCR works!!!!!

Cross posted from

CLR took a DCR some time back on how nullable types are implemented. See here and here to find out more about the DCR. I found from one of the internal DLs that the fix was already in the RTM bits.

I wrote a small piece of code which should work only with the DCR changes and kept it aside so once this DCR gets implemented I'd try it out. So each time I upgraded to a new build of VS/CLR I built/ran this code to see if it works. And it just did, with my todays upgrade to about 10 day old build in our lab. The new nullable type after becoming a basic runtime intrinsic just rocks. I have put in comment all the failures that used to happen previously with the same piece of code....

// this code works only with the latest bits of
// Visual Studio 2005 (C#2.0) and will fail to
// compile/run with older Beta2 bits

void Main(string[] args)
? val = 1;
int? nullval = null;

// this always worked
if (nullval == null
Console.WriteLine("It worked"

// this used to fail before and I think one of
// the biggest issue with the previous implementation
nullobj = nullval;
if(nullobj == null
Console.WriteLine("It worked"

// previously required
// box = Nullable.ToObject<int>(val); argh!!!!
box = val;

// If you do not need exceptional code
// (that's code that throws exception)
you needed to do int? unbox = Nullable.FromObject<int>(box);
int? unbox = (int
(unbox == val)
Console.WriteLine("It worked again"

int intval = (int)box;
(intval == val.Value)
Console.WriteLine("attained Nullable Nirvana"

int x = 10;
y = x;
// Previously Exception!!! cast is not valid
int? z = (int

IComparable c = val;
// Previously Exception!!! : object type cannot be
// converted to target type
(c.CompareTo(box) == 0)
Console.WriteLine("I have seen it all"

// compilation failure
> ic = val;
)box) == 0)
Console.WriteLine("Wow there is even more to see"

The output of the program is

It worked
It worked
It worked again
attained Nullable Nirvana
I have seen it all
Wow there is even more to see

No comments: