That's simple: don't use Nothing
when you store Doubles
in an array and don't use a Object()
when you actually want to store doubles.
Wait, it would be better to use a Double?()
anyway. Nullables can be initialized with null/Nothing
Then you don't need a cast at all.
Dim pArray As Double?() = {Nothing, 1.5, 2.27, -3.0}
Dim first = pArray(0)
If first.HasValue Then
' No, it's a Nullable(Of Double)/Double? without a value
End If
Edit According to your original question. The better question would be why this works in VB:
Dim d as Double = DirectCast(Nothing, Double) ' => 0.0
The reason: Nothing
in VB.Net is the equivalent of default(T)
in C#: the default value for the given type which is 0 for numeric types, Date.MinValue
for Date
and Nothing
(now in the meaning of null
in C#) for reference types.
So DirectCast(Nothing, Double)
will be converted implicitely to the Double
0. Whereas the Object()
contains really objects which is a placeholder for everything. But Nothing
is normally a "unknown" state of any object and not a double, so the DirectCast
which is very strict fails. It would also throw a runtime error if you would change the value -3.0
to -3
since that is actually an Integer
.
To cut a long story short,
use CType
instead of DirectCast
for those conversions and it'll work.
Dim obj As Object() = {Nothing, 1.0, 2}
Dim d1 = CType(obj(0), Double) ' => 0.0
Dim d2 = CType(obj(1), Double) ' => 1.0
Dim d3 = CType(obj(2), Double) ' => 2.0