0

Okay, so I'm no stranger to coding and this strikes me as absolutely silly. Maybe someone can shed some light on why this is failing as usually VB.Net is intuitive and flexible with this type (pun intended) of thing?

I have a simple example, where I want to pass an object set with an integer value of lets say 6 to a procedure with a nullable Int64 parameter. I'd like to do so as I can't change the incoming value from object, it is a property of a class and may very well be nothing, hence the nullable Int64 being used.

    Private Sub NullableParamTest(ByVal ID As Int64?)
        MsgBox(ID)
    End Sub

Now a simple sample like this will cause the exception:

    Dim objTest As Object = 6
    NullableParamTest(objTest)

Why is this not being boxed properly when the object is being set to an integer and passing to a procedure with an Int64? type? If I wrap the objTest with CInt(objTest) and cast it first it's fine, but I shouldn't need to do that at least in VB. I have logging methods that optionally take in various IDs as Int64? but the source is this Object property causing it to fail...even though they have perfectly valid Int64s set.

I wanted to avoid the whole Optional...Int64 = Nothing as that's not really setting it to nothing, granted it works as my IDs would never be zero but it's not true to what is really going on.

  • 1
    `Dim objTest As Object = 6&`. – GSerg Oct 21 '20 at 14:32
  • @GSerg Thank you, I believe it does, especially the link within that answer for that post. It just seems a bit odd that the compiler can't handle the conversion on the fly, I was hoping to not have to cast/convert, looks like going with Int64 knowing that 0 wouldn't be valid anyway or changing those params to Object are my only two options. Also thanks for the 6& notation, I don't recall having seen that anywhere and that does work as well! – SoulSeekkor Oct 21 '20 at 14:48

1 Answers1

0

Thanks to the comments from @GSerg, it appears the following is the answer to this question found here:

A boxed value can only be unboxed to a variable of the exact same type.

It links to another answer describing this behavior as being performance related. In short you have to convert/cast the value within the object first before passing it.

In my case my passed value of an ID would never be 0 so using a regular Int64 and checking that it's nothing would work, otherwise using Object for a type is the alternative as wrapping all of the method calls with over half a dozen converts would be hideous.

The other comment by @GSerg mentions the notation of adding an & after the value to make it an explicit Int64, also allowing it to work in this case. Note that casting the value in this way as an Int32, which in theory would work (as it fits within an Int64 space), in fact does not due to the first part of my comment that it has to be unboxed as the exact same value type for the parameter.