
How Do I convert (or cast) Structures?
Quote:
> How do I perform custom conversions for structures in vb.net?
> I have read that this is not supported. How do I convert, cast, or
> event copy the data between 2 different structures.
> I read one recommendation was to use a shared function, but I could
> not get it to work.
Here's a couple of structures that use a shared function to copy data
around. NOTE: Since you can't cast, the data copying is done manually
in code:
Option Strict
Imports System
Imports Microsoft.VisualBasic
Public Class App1
Structure S1
Public FirstName As String
Public LastName As String
Public Age As Integer
Shared Function FromS2(data As S2) As S1
Dim new_s1 As S1
Dim i As integer
i = Instr(data.Name, ",")
new_s1.LastName = Left(data.Name, i-1)
new_s1.FirstName = Mid(data.Name, i+1)
new_s1.Age = data.CurrentAge
Return new_s1
End Function
End Structure
Structure S2
Public Name As String
Public CurrentAge As Integer
End Structure
Shared Sub Main()
Dim p2 As S2
p2.Name = "Gunnerson,Eric"
p2.CurrentAge = 33
Dim p1 As S1 = S1.FromS2(p2)
Console.WriteLine("{0} {1}, Age: {2}", p1.FirstName, _
p1.LastName, p1.Age)
End Sub
End Class
--
Patrick Steele
Microsoft .NET MVP