Write Better Code; Using Nullable With C#
Written by Robert Greiner on April 20, 2010
I'm sure if you have ever written code for more than 45 seconds, you have more than likely come across a need to check whether or not a variable has been assigned a value. This is probably how about 99% of us do it: The above code is bad for three reasons:
- The code is error prone. Why do things on your own, when the language provides a simple consistent way of doing things?
- The code isn't standardized. What if you assign 0 as the official "un-assigned" check for all of your strings, but Johnny Programmer (in his super awesome wisdom) decides to initialize all of his un-assigned integers with -1, then what? Now you are forced to add unnecessary rules to your coding standards to ensure yours and Johnny's code plays together nicely. This is lame.
- The code isn't optimized. The fewest amount of bits to compare per if statement the better. why compare multiple Bytes when you can compare a simple boolean? This can end up costing you precious milliseconds.