Search code examples
vb.netinheritancesubclassing

Convert String to custom Class Type in Vb.net


Most of the search results I've found have turned up to be the opposite of what I'm looking for so here's my question:

I'm trying to convert System types into custom types of my own but as I mentioned, my search results have not been effective and give me the opposite of what i'm looking for.

Say I have a String of "mystringgoeshere" and a class like:

Class MyStringType

    Dim str As String

End Class
Dim s As MyStringType = "mystringgoeshere"

And i get this error {Value of type 'String' cannot be converted to 'Project1.MyStringType'.}

I don't have any code yet really because I have no idea how to achieve this, but essentially what I want to do is set the "s" object's "str" string using a method like what i have in the code block above. I've tried using a "new(data as String)" subroutine, but it doesn't work with what i am trying.

Any ideas? thx~


Solution

  • Looking at this VBCity Article on creating Custom Types It is using the Widening Operator.

    from last link:

    Widening conversions always succeed at run time and never incur data loss. Examples are Single to Double, Char to String, and a derived type to its base type.

    so try something like this

    Public Class Form1
    
        Public Sub New()
    
            ' This call is required by the designer.
            InitializeComponent()
    
            ' Add any initialization after the InitializeComponent() call.
            Dim s As MyStringType = "mystringgoeshere"
            Dim s1 As MyStringType = "Hello"
            Dim s2 As MyStringType = s1 + s
        End Sub
    End Class
    
    Class MyStringType
        Private _string As String
        Private Sub New(ByVal value As String)
            Me._string = value
        End Sub
        Public Shared Widening Operator CType(ByVal value As String) As MyStringType
            Return New MyStringType(value)
        End Operator
        Public Overrides Function ToString() As String
            Return _string
        End Function
        Public Shared Operator +(ByVal s1 As MyStringType, s2 As MyStringType) As MyStringType
            Dim temp As String = s1._string + s2._string
            Return New MyStringType(temp)
        End Operator
    End Class