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
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?
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
That didn’t work until I used this code in it: return StrComp(Self.MyString, OtherString, 0)
Thanks for your help!