How do I use a null value in a double in VB.Net 2010?
Solution 1
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
Solution 2
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.
evilspoons
I'm an electrical engineer that does automation. This means I end up dabbling in Windows programming for human-machine interfaces to control industrial machinery. I'm not extremely fluent in any PC-based programming languages, but I at least like to hold myself to high standards and attempt to learn the right way to do things instead of just hacking something together because it works.
Updated on June 11, 2022Comments
-
evilspoons almost 2 years
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
andSet
these values. It turns out I was doing things right except I left myProperty
's type as aDouble
instead of aDouble?
so it was casting back to zero instead of theNothing
value. Useful information still in the answers below, though! -
evilspoons over 12 yearsAha, 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 over 12 yearsGreat 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.