Operator_Convert Question


I have a main class ClassA. From it there are two subclasses ClassB and ClassC. Each of these subclasses has different constructors.

Now there is ClassTest with a Fill As ClassA property.

How can I shorten the previous assignment from this code (MyPicture = Picture)

Var instance As New ClassTest

instance.Fill = New ClassB(Color.Red)
' or
' instance.Fill = New ClassC(MyPicture)

to this notation using Operator_Convert?

Var instance As New ClassTest

instance.Fill = Color.Red
' or
' instance.Fill = MyPicture

So far I get a syntax error. Maybe @Kem_Tekinay?

Use the Assigns keyword instead of Operator_Convert. Make one method per datatype:

Sub Fill(Assigns c As Color)

Sub Fill(Assigns p As Picture)


1 Like

If Fill is a ClassA but you want to force a ClassB or ClassC, you can’t use Operator_Convert.

Why? They are both Subclasses. :frowning:

Good suggestion @Andrew_Lambert, thank. Since I have a couple of classes which habe ClassA Properties, this won’t be handy.

Fill As ClassA

ClassA has Operator_Convert(c As Color), so when you assign the Color to Fill, you will get an instance of ClassA. If you want an instance of ClassB, you’d have to do this:

var b as ClassB = Color.Red
instance.Fill = b

Which then in my case is almost the same as instance.Fill = New ClassB(Color.Red). Thanks.

1 Like

Another solution could be this.

Thanks to @Norman_Palardy. We can get it work the way I want adding the following Operator_Lookup to ClassTest:

Sub Operator_Lookup(name As String, Assigns newValue As Variant)
  Select Case name
  Case "Fill"
    If (newValue.Type = Variant.TypeColor) Then
      Fill = New ClassB(newValue.ColorValue)
    Elseif newValue.Type = Variant.TypeObject And newValue IsA Picture Then
      Fill = New ClassC(Picture(newValue.ObjectValue))
    End If
  End Select
End Sub

ClassB and ClassC need to get an Operator_Convert method. That’s all.

Warning: Operator_Lookup overrides the compilers checking in a way that you have to really know what you are doing as a lot of compiler error will not occur any more!