Apoorv Kansal
Apoorv Kansal

Reputation: 3280

Object Reference casting vb.net

I have no idea on how to cast an object that type was 'Object' to a user defined class type.

I have a private instance variable:

Private studyType as Object

What i need to do is to instantiate this object from an event handling method. And no, not to instance new Object().

Basically it would look like this:

studyType = new VCEOnly()

However, I am only allowed to use the Object class subs and functions as the type was defined as Object. So i need to cast it to VCEOnly class type so i can access its subs and functions.

Basically, studyType needs to be casted from Object to VCEOnly. I am not allowed to pre-define studyType as VCEOnly when declared.

Upvotes: 0

Views: 8065

Answers (2)

Tim De Belder
Tim De Belder

Reputation: 71

you can also use:

dim studyType as Object = new VCEOnly()    

...

dim studyTypeVCE as VCEOnly = nothing
if trycast(studytype,VCEOnly) IsNot Nothing then
   studyTypeVCE = DirectCast(studytype,VCEOnly)
   '... do your thing
end if

the if statement checks if the object can be casted to the wanted type and if so variable of type VCEOnly will be filled in with a cast of studytype.

Upvotes: 2

Matt Wilko
Matt Wilko

Reputation: 27322

Use CType to cast an object from one type to another

Something like this should do it:

Dim studyType as Object
Dim studyTypeVCE as New VCEOnly
studyTypeVCE = Ctype(studyType,VCEOnly)

or you can just do this:

With CType(studyType, VCEOnly)
    .SomeVCEOnlyProperty = "SomeValue"
End With

Upvotes: 1

Related Questions