Best way to "cast" base class to specialized class

  • Thread starter Thread starter SA
  • Start date Start date
S

SA

Hi all:

I have an object of a base class that needs to be cast to an object of a
specialized class.

What is the best way to do this? (I thought about creating a constructor in
the specialized class that takes an argument of the type of the base class
and then copy property values over, but that seems like a hassle)
 
Hi all:

I have an object of a base class that needs to be cast to an object of a
specialized class.

What is the best way to do this? (I thought about creating a constructor in
the specialized class that takes an argument of the type of the base class
and then copy property values over, but that seems like a hassle)

The first step would be to get the nomenclature right. The above
wouldn't cast the object, it would create a new object. If that's what
you want, a constructor or some kind of factory pattern is a reasonable
way to go, a Herfried's post contains a link to lots of info about this.

If casting is really what you want, VB.Net has a cast operator:

DirectCast(MyBaseObject, MySubClass)
 
David:

DirectCast (or CType) doesn't work... That only works from subclass to base
class, but not the other way around.
 
Herfried:

Thanks. Role pattern is not what I am after, so the constructor idea will
have to do then.
 
David:

DirectCast (or CType) doesn't work... That only works from subclass to base
class, but not the other way around.

No, that's not true, which is why I said you should understand the
nomenclature before trying to understand the options.

Like I said, if what you really want is a new object, then forget any
kind of analogy to "casting" and the problem gets a lot easier.
 
David:

Not sure how the nomenclature could get confusing... I don't want a new
object, but I end up creating one because casting an object from the base
class to a sub class is not supported.

Public Class A
End Class

Public Class B
Inherits A
End Class

Dim objA As New A
Dim objB As New B

You can write

objA = objB
objA = DirectCast(objB, A)
objA = CType(objB, A)

but not

B = A
objB = DirectCast(objA, B)
objB = CType(objA, B)

Note that no compiler warnings occur, but there are runtime exceptions
thrown (InvalidCastException). So, yes, it *is* true that you can't cast an
object from a base class to an object of a subclass of that base class.

In the end, that makes sense, because you could get around any restrictions
on required property values that have been imposed on objects of the
subclass type of course... Still, it would be nice to be able to just cast.
 

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

Back
Top