I have an VB6 application which uses LSet()
with two user defined data types (Type), to assign data from one type to another, e.g.:
Lset type1 = Type2
Now I have to apply equivalent logic in VB.net. However, in VB.net, LSet cannot be used against different types (Types in VB6).
How can I implement the VB6 LSet logic in VB.net?
Sample / typical code:
Public MQ_Policy As typPolicyDataRetrieval
Public typPolicyDataBlock As gtypPolicyDataBlock
With MQ_Policy.Input
.PcPolicyIDNum = Mid(InputString, 1, 8)
.PcPolicyIDNumPrefix = " "
.Datalength = Format$(CLng(Len(MQ_Policy)) - (Len(MQ_Policy.MQHeader) + Len(MQ_Policy.Input.Datalength)), String$(Len(.Datalength), "0"))
End With
LSet typPolicyDataBlock = MQ_Policy
Appreciate all your help.
You shouldn't be doing that in VB.NET.
There are other ways, such as defining conversion operators from one type to another and then using them in the code:
Private Structure t1
Public a As Short
Public b As Short
End Structure
Private Structure t2
Public v As Integer
Public Shared Widening Operator CType(ByVal v As t1) As t2
Return New t2 With {.v = v.a Or (CType(v.b, Integer) << 16)}
End Operator
End Structure
Sub Main()
Dim v1 As t1, v2 As t2
v2 = v1 ' Works!
End Sub
However, if you are damn sure you should perform a bytewise copy, and you are aware of the alignment issues and are happy with them, then you can do so:
Imports System.Runtime.InteropServices
Public Function CopyStructure(ByVal s As Object, ByVal ResultType As System.Type) As Object
Dim h As GCHandle
Try
h = GCHandle.Alloc(s, GCHandleType.Pinned)
Return Marshal.PtrToStructure(h.AddrOfPinnedObject, ResultType)
Finally
If h.IsAllocated Then h.Free()
End Try
End Function
Sub Main()
Dim v1 As t1, v2 As t2
v2 = DirectCast(CopyStructure(v1, GetType(t2)), t2)
End Sub
See a better answer here: Converting VB6 Custom Type (with Fixed Length Strings) to VB .NET
In short LSet, when used with types, copies memory from one place to another! So it should NOT be used under any circumstances. The original code is not good so converting it 'as is' will be a bad idea.
That said you should be able to replace it with either a Cast if the objects are compatible or write a converter function to change the type manually.