CType and downcasting classes


R

Random

I'm trying to find the method I need to explicitly cast a class to a type of
one of the classes that inherits from it. I'm passing in the type of the
class I want to cast to as a parameter of my method, but the procedure
doesn't me using this. Here's the simplified code....
----------------------
Public Class MyClass
....
End Class

Public Class MyDerivedClass
Inherits MyClass
....
End Class

Public Shared Function GetClass(ByVal classType As MyClass) As MyClass
dim sC As MyClass = New MyClass()
Return CType(sC, classType)
End Function
 
Ad

Advertisements

K

Karl Seguin

I'm pretty sure you can't do what you are trying to do.

sC is of type MyClass...you can't magically convert it to anything IT
doesn't inherit (in this case Object).

What you likely want to do (atleast from what I can tell), is to create an
instance based on a Type.

Soemthing like:

public shared function GetClass(ByVal type as Type) as MyClass
if type is nothing then
throw new ArgumentNullException("type")
end if

if !type.IsInstanceOfType(typeof(MyClass)) then
'throw an exception
end if

return (MyClass) Activator.CreateInstance(type)
end function

Karl
 
Ad

Advertisements

R

Random

Thanks. I ended up doing something pretty close after discovering Generics
yesterday. A lot cleaner than what I was trying to do....

Public Shared Function GetClass(Of T As MyClass)(ByVal arg1 As String) As T
dim sT As Type = GetType(T)
dim sC As MyClass = Activator.CreateInstance(sT)
return sC
End Function

....then my code calls the function like so:

dim NewClass As MyDerivedClass = GetClass(Of MyDerivedClass)("some
parameter")

It's really quite cool and opened up a world of other ways I'm going to
start using Generics in the app
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top