DOODC84 DOODC84 - 5 months ago 36
Vb.net Question

Visual Basic - stack overflow from object references

I'm making a little text based adventure game in VB and I have different classes for different functions in the game (to keep organized). Well, I need two classes to reference each other. I'll explain.

So these two classes are

Direct.vb
and
Commands.vb
. I created references in the files so that they could execute methods in each other's code.

Direct.vb
references
Commands.vb
like so:

Dim comm As New Commands


And then
Commands.vb
references
Direct.vb
in the same way.

Dim dir As New Direct


But when I run the program to see if it works, it throws a
StackOverflowException
. I think these classes are doing an infinite loop of references.

Is there a way I can fix this?

Answer

You can reference one class from the other, but you can't have them both create a new instance of the other.

In your current case, say you create one Commands, this creates one Direct, this creates one Commands, this creates one Direct, etc., etc. This will fill the heap and the stack, but the stack runs out first with constructor functions.

The solution is to use a reference only, so omit the New keyword from at least one of these classes. Without knowing the specifics, it's not really possible to give more specific advise. Typically, though, this kind of construction would work:

Public Class Commands
   Private dir As Direct

   Public Sub New()
       dir = New Direct(Me)
   End Sub
End Class

Public Class Direct
    Private cmd As Commands

    Public Sub New(ByVal cmdInstance As Commands)
        cmd = cmdInstance
    End Sub
End Class
Comments