Thursday, November 20, 2008

Clarity of intent and newing up structs

Sometimes it is useful to see if a struct hasn't been set.  Of course this can get you into trouble if the unset value is a legal value, but sometimes it's not, like when dividing an int 0 will throw.

Previously I had been using code like if (divisor != new int() ) to check the value prior to calling my function.

This struck me as very odd to be newing up a struct.

Then I recalled the default keyword, which I'd only used for generics before.  It turns out default works the same and declares intent better.

if (divisor != default(int) )


Of course in this contrived example it makes more sense to do != 0, but when more complex structs are involved the syntax works quite nicely.

No comments: