6

Straightforward question: I have a few variables that are doubles. I would like to be able to store a "null" state in them, i.e. I need to be able to represent that the variable doesn't contain valid data. I'd really rather not associate a boolean "is valid" variable with every single double, that would be ugly and likely unnecessary.

First, I found out that one has to declare the variable differently to allow the concept of 'IsNothing' to be checked, so I do this:

dim someDouble as Double?

(Note the question mark). If I don't declare it like that, the error check gives me a "IsNot requires operands that have reference types" message.

Once declared, setting the variable to...

someDouble = Nothing

...seems to set it to zero, because it never runs the code in my if/else statement that checks whether someDouble IsNot Nothing... which is bad because the variable can legitimately store a 0 as a valid piece of data.

What am I missing here? Thanks!

EDIT: I left out that I was using properties in a class to Get and Set these values. It turns out I was doing things right except I left my Property's type as a Double instead of a Double? so it was casting back to zero instead of the Nothing value. Useful information still in the answers below, though!

evilspoons
  • 405
  • 2
  • 6
  • 16

2 Answers2

7

you should go read on Nullable Structure on MSDN

this will explain how to use it

example:

Sub Main()
    Dim someDouble As Double?

    someDouble = Nothing
    If someDouble.HasValue Then
        Console.WriteLine(someDouble.ToString)
    Else
        Console.WriteLine("someDouble is nothing / null")
    End If
    Console.Read()
End Sub
Fredou
  • 19,848
  • 10
  • 58
  • 113
  • Aha, this is essentially what I was already doing... except I goofed up and forgot to change my *Property* to type 'Double?' from 'Double' so it was casting it back to a standard 'Double' when doing the 'Set'. Argh! Thanks for the link! – evilspoons Jan 03 '12 at 20:12
5

While I do not know what is causing your problems with "Nothing", you could also use "Double.NaN" (Not a Number) instead. This would also not require the special "Double?" declaration.

RBarryYoung
  • 55,398
  • 14
  • 96
  • 137
  • Great idea! I think I will try this instead of the Nothing (null) approach. See my comment on Fredou's answer for why it wasn't working with Nothing, though. – evilspoons Jan 03 '12 at 20:14