How to create new instance of a class / Type mismatch error

  1. 3 months ago

    I have created a custom class object and understand how to create a new instance of it by either having "new" in the declaration (Dim myObj As New CustomObj) or using "new" on the fly (myObj = new CustomObj("hello world")) if it wasn't included in the declaration and handling the string parameter in the constructor, but is it possible to achieve this on the fly through myObj = "hello world" without the "new" bit and without throwing an error?

    Even with "new" in the declaration when I try to assign it a string value (myObj = "hello world") I get the compile error "Type mismatch error. Expected class CustomObj, but got TextLiteral"

    Any ideas?

    Add an Operator_Convert method to the class. Operator_Convert is a special method name that overloads the conversion operator (=), and will instantiate the object implicitly. You can then handle the string parameter there or call the Constructor as a normal method:

    Sub Operator_Convert(FromData As String)
       Me.Constructor(FromData)
    End Sub
  2. Andrew L

    Mar 9 Answer San Francisco, CA, USA

    Add an Operator_Convert method to the class. Operator_Convert is a special method name that overloads the conversion operator (=), and will instantiate the object implicitly. You can then handle the string parameter there or call the Constructor as a normal method:

    Sub Operator_Convert(FromData As String)
       Me.Constructor(FromData)
    End Sub
  3. Thanks, Andrew. That works! But now when I try... If myObj <> "hello world" then it throws an undefined operator error.

    I assume I have to add Operator_Compare? What code would be in this method?

  4. Andrew L

    Mar 9 San Francisco, CA, USA
    Edited 3 months ago

    Try:

    Function Operator_Compare(OtherString As String) As Integer
       ' if equal return 0
       ' if self > OtherString return 1
       ' if self < OtherString return -1
    End Function
  5. That didn't work until I used this code in it: return StrComp(Self.MyString, OtherString, 0)

    Thanks for your help!

or Sign Up to reply!