Question

I've written an own type and I would like to use the property members that the type has, when I try to cast my own type to an object.

I've tried with Ctype and also with DirectCast/TryCast but Intellisense does not show me the type members so I can't use it.

So ...There is a way to do this?, this is the code that I'm using (See the comment lines):

private sub SomeSub

    ' I declare a variable as Object/Undefined type, I couldn't change this.
    Dim SomeVar As Object = Nothing

    select case SomeEnumValue

        case SomeEnum.Value1
            SomeVar = CStr("Some String") ' A String type

        case SomeEnum.Value2
            SomeVar = CLng(1L) ' A Long type

        case SomeEnum.Value3
            SomeVar = CType(SomeVar, MyOwntype) ' My Own Type

            ' So here I would like to be able to use the object members,
            ' instead of the need to use Ctype like this:

            SomeControl.Text = CType(SomeVar, MyOwntype).Property

    end select

end sub
Was it helpful?

Solution 2

Remember that casting a reference-type object does not actually convert the object at all. All casting does is to alter the lens (interface) through which you are accessing the object. With that in mind, the following line is totally useless:

SomeVar = CType(action, MyOwntype)

SomeVar is As Object, therefore, casting the object to any particular type first, before setting SomeVar, is pointless. Once SomeVar is pointing to it, it will be viewing it As Object, regardless of the interface through which it was previously viewed/referenced.

The way to do what you want to do would be to create a new variable of the specific type and set that variable to the object. If you have Option Strict On, as you most likely ought to, you'll need to cast it when you set the variable. But, once you have set the variable, then you can access the object through that variable (with full intellisense) without having to re-cast each time. For instance:

Dim mySpecificVar As MyOwnType = DirectCast(action, MyOwnType)
SomeControl.Text = mySpecificVar.Property
' ...

OTHER TIPS

You can store CType result in local variable and use it to access your properties

Dim myObj As MyOwnType = CType(SomeVar, MyOwnType)
SomeControl.Text = myObj.Property

If you want to use the properties, you have to cast it back onto the type MyOwnType, as in:

SomeControl.Text = DirectCast(SomeVar, MyOwntype).Property

You can't use the SomeVar by itself because it's of type Object which doesn't have your custom properties.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top