-1

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.

Lazy Turtle
  • 93
  • 1
  • 8
  • 1
    I don't quite follow, what is the problem you are having? You can add instances of player class to that list if that is what you are asking? Also this code does not seem to throw InvalidCastException but a NullReferenceException since the list is not initialized. – Esko Jun 10 '19 at 11:27
  • 1
    turn option strict on and fix the errors that show up https://stackoverflow.com/questions/5160669/option-strict-on-by-default-in-vb-net – Slai Jun 10 '19 at 11:31

1 Answers1

0

I have misinterpreted the cause of the error as being adding to a list where the actual cause was the instantiation of the list

New List(of instance)(new player(0,4))

I fixed this by separating the assignment and the declaration of the list.

Dim lstInstances As New List(Of instance)
lstInstances.Add(new player(0,4))
Lazy Turtle
  • 93
  • 1
  • 8
  • 1
    You code as posted still shouldn't work - have you created a constructor in the `person` class since posting it? – David Wilson Jun 10 '19 at 22:40
  • Sorry I didn't include this in the class I showed as I didn't think it was relevant. The base class has a constructor for it and the child inherits this. Hope this helps anyone in future : ) – Lazy Turtle Jun 11 '19 at 08:17