Nullable(Of Single) VB.NET - Setting = 0 results in Nothing

  • Thread starter Thread starter BobRoyAce
  • Start date Start date
B

BobRoyAce

I am using VB.NET and I have a variable that is defined as Nullable(Of
Single) as follows:

Dim fMyNullableSingle as Nullable(Of Single)

Then, I have another variable as follows:

Dim fCumulativeExpectedAmt As Single = 0

When I make the following assignment:

fMyNullableSingle = fCumulativeExpectedAmt

the end result is that fMyNullableSingle is Nothing. So, later, when I
try to assign it to another non-nullable variable, it fails.For
example...

Dim fMyNonNullableSingle as Single
fMyNonNullableSingle = fMyNullableSingle

causes an Exception.

How do I correct this?
 
I am using VB.NET and I have a variable that is defined as Nullable(Of
Single) as follows:

  Dim fMyNullableSingle as Nullable(Of Single)

Then, I have another variable as follows:

  Dim fCumulativeExpectedAmt As Single = 0

When I make the following assignment:

  fMyNullableSingle = fCumulativeExpectedAmt

the end result is that fMyNullableSingle is Nothing.

I don't get that, when I assign zero to the Nullable(Of Single) it
returns zero:

////////////
Module Module1

Sub Main()
Dim s As Nullable(Of Single)
Dim s2 As Single = 0

Console.WriteLine(s.HasValue)
If s.HasValue Then Console.WriteLine(s.Value)

s = s2

Console.WriteLine(s.HasValue)
If s.HasValue Then Console.WriteLine(s.Value)

Console.Read()
End Sub

End Module
////////////
So, later, when I
try to assign it to another non-nullable variable, it fails.For
example...

  Dim fMyNonNullableSingle as Single
  fMyNonNullableSingle = fMyNullableSingle

causes an Exception.

How do I correct this?

It should cause an exception - that's an invalid cast. Simply do the
following to correct the problem:

//////////////
fMyNonNullableSingle = fMyNullableSingle.Value
//////////////

Thanks,

Seth Rowe [MVP]
http://sethrowe.blogspot.com/
 
I don't get that, when I assign zero to the Nullable(Of Single) it
returns zero:
I erred in not mentioning that the setting was happening in a Property
Set, and therein was the problem. The code that I had there was
checking, incorrectly, to see if the new value was different from the
existing value, and only setting the property if it was actually
different. Well, the code to check for difference did not use
the .Equals method of the Nullable type, and so was never setting the
property equal to ZERO! My mistake...
It should cause an exception - that's an invalid cast. Simply do the
following to correct the problem:

//////////////
fMyNonNullableSingle = fMyNullableSingle.Value
//////////////

I have equated variables like this many times, without the
explicit .Value at the end of the Nullable one, with no known
problems. Perhaps it's just more "proper" to use the .Value?
 
Back
Top