[C#] Problem performing math with nullable types

Started by
2 comments, last by benryves 16 years, 8 months ago
Here is my problem, in general terms: 1. First I perform a database query that returns values that at some point are guaranteed to be "null." I have no control over this. 2. Second, I pass the returned values as paramaters into a method as nullable types. 3. Third, Inside the method I perform math on these values, then display them. MY PROBLEM: An exception is thrown each time the method tries to perform math on a null value. MY WORKAROUND, I created a bunch of if statements at the beginning of the method that tests each parameter to see if it's null. If it is, it sets that parameter value to "0." This makes me cringe, however, as it seems like a very inelegant solution to the problem. Does anyone know a better way to solve this problem? I'd appreciate any direction...
Advertisement
Nullable types have a method GetValueOrDefault which does the "if null use 0" bit of logic
.NET never ceases to amaze me. Thanks!
C# also has the null-coalescing operator ??. This might be useful if you don't want to return default(T).

[Website] [+++ Divide By Cucumber Error. Please Reinstall Universe And Reboot +++]

This topic is closed to new replies.

Advertisement