Operator_Convert

From TOF

@hansklok

Operator_convert can be used in both a CONVERT TO and CONVERT FROM style
The CONVERT TO style is one with a return type - not the one in use here

The convert FROM is more like a CONSTRUCTOR
In this case you COULD make operator convert work like

Var instance As ClassTest

instance = Color.Red // creates a new instance with the Fill set to Color.Red
' or
instance = MyPicture // creates a new instance with the Fill set to MyPicture

Here’s a quick sample of this in action

https://www.great-white-software.com/blog/2020/03/30/operator_convert-2/
https://www.great-white-software.com/blog/2019/12/05/operator_convert/
https://www.great-white-software.com/blog/2021/02/09/convert-to-or-convert-from/

The other way to make this work is the use of operator_lookup :stuck_out_tongue:

Class ClassTest
     sub operator_lookup(name as string, assigns v as variant)
          select case name
              case "Fill"
                   If (newValue.Type = Variant.TypeColor) Then
                      mFill = New ClassB(newValue.ColorValue)
                  Elseif newValue.Type = Variant.TypeObject And newValue IsA Picture Then
                      mFill = New ClassC(Picture(newValue.ObjectValue))
                  End If
            Else
               Break
         End Select
     end sub

     protected property mFill as ClassA
end class

and now you can write

Var instance As ClassTest

instance.Fill = Color.Red // creates a new instance with the Fill set to Color.Red
' or
instance.Fill = MyPicture //

BUT code like

Var instance As ClassTest
 // compiles & runs as we have appropriate code in operator_lookup for the Fill property
instance.Fill = Color.Orange

// compiles but DOES NOT RUN as operator_lookup has no code for this
// and the compiler WILL NOT complain or warn about no such property !
instance.foobar = 1

So BE CAREFUL with the use of operator_lookup

1 Like

Another way to solve this is method pairs (or maybe a computed property)

Class ClassTest
     sub Fill( assigns value as color )
        mFill = New ClassB(value)
     end sub
     sub Fill( assigns value as picture )
         mFill = New ClassC(value)
     end sub
     function Fill() as ClassA
        return mFill
     end function
    
     protected property mFill as ClassA
end class

which lets you do

Var instance As ClassTest

instance.Fill = Color.Red // creates a new instance with the Fill set to Color.Red
' or
instance.Fill = MyPicture //

and you will still get compile errors, type mismatch errors, etc

operator_convert is not needed
nor is operator_lookup

1 Like