Friday, May 28, 2004

I’m just not sure I like the nullable type syntax in C# 2.0. Every time I see the shortcut syntax for a nullable type, I cringe a bit.

int? i = 2112; // cringe

The first thought that struck me when I saw this was that C# language now has some decent material for obfuscation contents. C obfuscation contests have been around awhile, and tools like the preprocessor give C programmers plenty of material to work with. For example, I’d never be able to look at this source code and guess that when compiled it plays a game of adventure. It’s both repulsive and fascinating at the same time.

I tried to get comfortable with the new syntax in the May CTP, but I keep getting compiler errors on simple examples:

int? x = 125;
int? y = 33;
int? z = x + y;

Error: "Operator '+' cannot be applied to operands of type 'System.Nullable' and 'System.Nullable'"

I’m thinking nullable type support hasn’t completely made it. The null coalescing operator ( ?? ) doesn’t appear to work yet either:

   int? x = null;
   int? y = 15;
   int? z = x ?? y; //cringe

"Operator '??' cannot be applied to operands of type 'System.Nullable' and 'System.Nullable'"

Then I thought I’d have some fun and try to see what I could break (warning, this is really vulgar):

  using c = System.Console;
  class P
    delegate int?? p();
    delegate int? u(int?? x);
    delegate int u2(int?? x);
    static void Main(string[] args)
      int?? j = new int??(1);
      int? k = null;
      int i = new int();
      p p; p = delegate { c.WriteLine(i); return new int??(new int?(i)); };      
      u u; u = delegate(int?? x) { return x.Value; };
      u2 u2; u2 = delegate(int?? x) { return u(x).Value; };
        i = i + u2(j);
      } while (u(p()).Value > 9 ? false : true);

But, the above executes and prints integers from 1 to 10. I was hoping for fireworks.

I’m still not comfortable with the new syntax, but it looks like I’ll have to wait till the next release to give it a more serious try. I’m surprised nullable types appeared so late in the cycle. Changes like this should come around early and entertain plenty of discussions and flame wars. I’m hoping it doesn’t come out feeling like a bolted-on solution that we have to live with for years.

Ooh, this just in. I have definite problems using MSDN help in the CTP, but RobCaron has the solution. Thank you, thank you, thank you, Rob.

Comments are closed.

My Pluralsight Courses

K.Scott Allen OdeToCode by K. Scott Allen
What JavaScript Developers Should Know About ECMAScript 2015
The Podcast!