Friday, August 22, 2008

Wait Wait What? Nullable Types in C# 2.0?

So I just learned that C# 2.0 has nullable types. You can do this:

int? i = null;

And it works fine. I know the idea is that you can represent a non-answer or unknown entity this way, especially when dealing with databases and DBNull. Still, it seems like a bad idea in a lot of ways. I've spoken out against nulls before when dealing with booleans. But what about integers?

I don't like it. I'm all about conceptual integrity; one thing is one thing. So what is an integer? A whole number. Is null a whole number? No it's not.

So what's the flipside? Sometimes nulls exist. You're going to do a left-join one day, and then your integer column "reset_count" is going to be null. Now you have to code to use the "hasValue" boolean attached to the nullable int (you get "hasValue" for free with every nullable-type declaration). Every time you want to use that value, you have to add code:

if (i.hasValue)

If you have to add that code, then you really have to refactor your code. Whatever you're representing should be able to handle this one-to-zero-or-more relationship without special code. Maybe use a collection and "foreach" through it. Maybe you do something cool that I've never heard of. But if you have to code for nulls, please seriously consider refactoring.

Appendix: I can think of one condition where you might need to add your own "valueSpecified" boolean: classes that represent XSDs with optional attributes. I don't have to like it though.
Post a Comment
All rights reserved. Take that!