Monday, October 15, 2007

small refactoring for working with nullable types

the article applies to: C# 2.0

C# 2.0 brought a new feature: nullable types, you already know they are cool and have been using them for a while, however, how many times have you seen (or written) something like:

//SomeClass.SomeObject.BoolProperty is of type bool?

if (SomeClass.SomeObject.BoolProperty.HasValue && SomeClass.SomeObject.BoolProperty.Value)...

because you can't write:
if (SomeClass.SomeObject.BoolProperty)...

That will not compile

The problem I have with that code is that it is repetitive, and is long, so what can we do?
you can write this instead:

if (SomeClass.SomeObject.BoolProperty??false)

much better, isn't? if BoolProperty has a value and the value is true, it will return true, otherwise it will return false; now, of course you can use the same technique with other types:

string firstName;
public string FirstName { get{ return firstName??""; }}

this code would ensure that FirstName will never be null (I'm pretty sure you've seen lots of "object reference not set blablabla" because of this)

Other examples:
int? result;
return result??-1; //if result was not set, return -1
bool? result;
return result??false;

That's it, hope you find it useful
Remember that the best code, is no code at all

kick it on


Steven said...

if (SomeClass. SomeObject. BoolProperty == true)
// also does the trick. :-)

BlackTigerX said...

true, that might be the preferred way for comparissons

int? y;
if (y == 0)...