How to use null value in double in VB.Net 2010?

A simple question: I have several variables that are doubles. I would like to be able to store the “zero” state in them, that is, I need to be able to imagine that the variable does not contain reliable data. I would prefer not to associate a boolean "valid" variable with every double, which would be ugly and probably not necessary.

First, I found that I need to declare a variable in different ways to allow the concept of "IsNothing" to be verified, so I do this:

dim someDouble as Double?

(Pay attention to the question mark). If I don't declare it like this, error checking gives me the message "IsNot requires operands that have reference types."

After the declaration, setting the variable to ...

someDouble = Nothing

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

What am I missing here? Thank!

EDIT: I forgot that I used properties in the class for Getand Setthese values. It turns out that I did everything correctly, except that I left my Propertytype as Doubleinstead Double?, so it returned to zero instead of value Nothing. Useful information is still in the answers below though!

+5
source share
2 answers

you should read 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
+7

, "Nothing", "Double.NaN" (Not a Number). "Double?". .

+4

All Articles