VB.NET - Want to add together two nullable types - how? (i.e. var1 + var2 where both are nullable and vari1=Nothing, Var2=5 results in Nothing)

StackOverflow https://stackoverflow.com/questions/3586039

  •  01-10-2019
  •  | 
  •  

Question

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)

Was it helpful?

Solution

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.

OTHER TIPS

nVar1.GetValueOrDefault()+ nVar2.GetValueOrDefault()

Or in c#:

(nVar1??0)+(nVar2??0)

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top