Tuesday, July 28, 2009

[C#] Is using nullable types for every variable a good programming skill?

In C#, is using nullable types for every variable a good programming skill?





For example, instead of setting every int / double to 0, char to \0, or string to "", should I use nullable types to set these variables to null?

[C#] Is using nullable types for every variable a good programming skill?
I would say its not a good idea. Whether you use nullable types depends on if it makes sense for that variable to be null.





If it needs to be created earlier but assigned a value later, then a nullable variable makes sense.





Some times a null value can take on a meaning of its own. In other words null can be just as valid value as an assigned value. Take for example a variable call average_age. What happens if there is no people? is the average 0? No its not. an average of 0 would imply some number of new born people. The best way would be to assign it to null because there really is no value. But null is still a value and no less important than an actual value. Theres a place for this kind of use for null, but it also could be abused.





But now take an example of a variable called number_of_people. Does a null value make any sense here? Well maybe in some circumstances it does, but in most it wouldn't. Just like a negative number wouldn't really make sense either.





Last note: Always write your code so that some one that is not you can look at it and understand what you were thinking. The way you "type" your variables will be something that will help that person understand.
Reply:http://blogs.msdn.com/csharpfaq/archive/...


No comments:

Post a Comment