views:

46

answers:

3

I have:

Dim nVar1 As Long?

Dim nVar2 As Long?

Dim nVarSum As Long?

nVar1 = Nothing

nVar2 = 5

nVarSum = nVar1 + nVar2

I would prefer the result to end with nVarSum being 5, instead of Nothing.

I understand if you add something to an unknown value, you will end up with "somthing + unknown" or x+5 will always equal "x+5" not "5" because you are still carrying around that unknown "x".

However, how can I effectively treat an unknown or Nothing as a zero for the purposes of addition in this case?

Thanks!

(What is basically happening is that the end user is sending us a data file, this code parses that file and then sums together about 15 fields. If the user leaves those fields blank instead of assigning a zero to them, I need to treat it as if it was a zero for this one addition operation, but all the rest of the code needs to continue seeing it as a Nothing value since the user did not ACTUALLY submit zero... they submitted blank or nothing)

+2  A: 

I think the simplest way is to use the If operator to coerce Nothing values into a default one.

nVarSum = If(nVar1,0) + If(nVar2,0)

The If operator in the 2 argument form when applied to nullable types essentially does the following. If the nullable has a value then the return is the value, otherwise it's the second argument.

JaredPar
I hate when languages add ambiguous operators.
ChaosPandion
@Chaos, how is this ambiguous? It's the VB equivalent of C#'s null coallescing operator.
JaredPar
@JaredPar - `If(Boolean, TrueValue, FalseValue)`?
ChaosPandion
@Chaos how is this ambiguous? It's well defined. Note: There are 2 `If` operators now. The one you described and the null coalescing version in my answer.
JaredPar
Overloaded operator, but not ambiguous.
Marc Gravell
@Jared, @Marc - OK, semantics aside I still don't like it.
ChaosPandion
What if I wanted to do the exact same thing, but the values had "-1" instead of "Nothing" as their value?Would I just be stuck using an IIF statement then over what you have done with If?(Assuming instead of a Nullable type, they used a -1 to mean NULL and assuming the values would only hold zero or positive values so -1 was a "safe" place holder for Nothing/Null/Blank...safe until someone tries to add them together of course)
Maxer
+3  A: 
nVar1.GetValueOrDefault()+ nVar2.GetValueOrDefault()

Or in c#:

(nVar1??0)+(nVar2??0)
Marc Gravell
A: 

Or explicitly test for nothing and set your default value. Same result as other answers posted.

If nVar1 is nothing then
   nVar1 = 0
end if

nVarSum = nVar1 + nVar2
Beth
I think I will have to use the If operator, because I can't change the actual value of nVar1 (I added an edit after the fact explaining the context). That nothing value needs to be preserved for use later on in the code, etc...Otherwise, I completely agree with setting it to zero and being done with it.
Maxer