views:

32

answers:

1

I have a MustInherit Parent class with two Child classes which Inherit from the Parent.

How can I use (or Cast) Me in a Parent function as the the child type of that instance?

EDIT: My actual goal is to be able to serialize (BinaryFormatter.Serialize(Stream, Object)) either of my child classes. However, "repeating the code" in each child "seems" wrong.

EDIT2: This is my Serialize function. Where should I implement this function? Copying and pasting to each child doesn't seem right, but casting the parent to a child doesn't seem right either.

Public Function Serialize() As Byte()
    Dim bFmt As New BinaryFormatter()
    Dim mStr As New MemoryStream()

    bFmt.Serialize(mStr, Me)

    Return mStr.ToArray()
End Function
A: 

To answer your question: Just as you would cast a normal object:

If TypeOf Me Is ChildClass1 Then
    Dim x As ChildClass1 = DirectCast(Me, ChildClass1)
    ....
End If

Still, doing such a cast in the code of Parent is considered very bad practice. Please have a look at the Template pattern, it might be more suitable to what you need, and it's way cleaner than doing such a cast.

Heinzi
Where should my serialize function be?
Steven
@Steven: In the parent -- *only* in the Parent. Yes, it will serialize the fields of the child as well if the *actual* type of the variable is `ChildClass1`. `BinaryFormatter.Serialize` uses the *dynamic* type of the object passed to it, not the static type of the variable.
Heinzi