I have created a list with the type of the parent class to loop through the same methods for each item. I would like to understand the best practise to iterate through these child classes.
From what I have read I can:
- Iterate through each type separately (My worst case scenario)
- Implement an IEnumerator on the parent class
- Create a wrapper class to contain all of children
But I may be wrong about these methods
The example is a simple cases I have came across with this issue. I would like to know the best way to handle this with a simple case like this or 4+ sub classes of a parent class with a flexible number of any.
Class instance
public Property intX As Short = 0
public Property intY As Short = 0
Sub New(X As Integer, Y As Integer)
intY = Y
intX = X
End Sub
End Class
Class player
Inherits instance
Public Sub move(key As ConsoleKeyInfo)
Select Case key.KeyChar
Case "w"
intY -= 1
Case "a"
intX -= 1
Case "s"
intY += 1
Case "d"
intX += 1
Case Else
Environment.Exit(0)
End Select
End Sub
lstInstance As List(Of instance)
for each instance In lstInstance
Console.SetCursorPosition(instance.intX, instance.intY)
next
I expected the list to accept child classes when setting the type to the parent. I instead encountered the run time exception System.InvalidCastException.