Previous | Index | Next 

[INFO] UDT fields accessed via a VB6Variant variable are readonly

Note: this article only applies to conversions to VB.NET, because the VB6Variant type isn’t supported when converting to C#.

In VB6 is possible to assign a user-defined type (UDT) to a Variant variable and then access the UDT fields in late-bound mode. VB.NET supports this technique if the Variant is converted to an Object variable, but not to a variable of another type, including the special VB6Variant type. Consider the following code:

        Dim udt As TestUDT, var As Variant
        var = udt
        udt.Name = "foo"     ' assignment in early-bound mode
        MsgBox var.Name      ' reading in late-bound mode
        var.Name = "bar"     ' assignment in late-bound mode

This is how VB Migration Partner translates the above code:

        Dim udt As TestUDT
        Dim var As Object = udt
        udt.Name = "foo"     ' assignment in early-bound mode
        MsgBox6(var.Name)    ' reading in late-bound mode
        var.Name = "bar"     ' assignment in late-bound mode

This code works fine under VB.NET and behaves exactly as in VB6. Next, lets use a ChangeType pragma to render the Variant variable using the VB6Variant type:

        '## ChangeType Variant, VB6Variant

The code the VB Migration Partner produces is slightly different:

        Dim udt As TestUDT
        ' UPGRADE_WARNING (#0414): Fields in a user-defined type stored in a VB6Variant variable 
           can't be written to.
        Dim var As Object = CVar6(udt)
        udt.Value.Name = "foo"     ' assignment in early-bound mode
        MsgBox6(var.Value.Name)    ' reading in late-bound mode
        var.Value.Name = "bar"     ' assignment in late-bound mode

The VB.NET code initially works as in VB6, except its last statement throws the following exception:

        Late-bound assignment to a field of value type 'TestUDT' is not valid when 'TestUDT' is 
           the result of a late-bound expression.

There is no known workaround to this issue. The bottom line is that you should never assign a UDT to a VB6Variant variable if you later need to modify that UDT’s fields. For this reason you should carefully scrutinize all messages 0414 that VB Migration Partner emits when it assigns a UDT to a VB6Variant variable.

 

Previous | Index | Next