Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a null value in a double in VB.Net 2010?

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!

like image 433
evilspoons Avatar asked Jan 03 '12 19:01

evilspoons


2 Answers

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
like image 196
Fredou Avatar answered Oct 12 '22 19:10

Fredou


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.

like image 38
RBarryYoung Avatar answered Oct 12 '22 17:10

RBarryYoung