Search code examples
vb.netooprecursionstack-overflowcircular-reference

VB.NET My class properties ends up in Circular references and thus StackOverflow exception


I have 2 classess. Role and User like this

Role

Public Class Role
    Public Property RoleID As Integer
    Public Property CreatedBy As User

    Sub New()    
        If Me.CreatedBy Is Nothing Then
            Me.CreatedBy = New User()
        End If
End Class

User

Public Class User
    Public Property UserID As Integer
    Public Property Role As Role

  Public Sub New()
        If Me.Role Is Nothing Then
            Me.Role = New Role()
        End If
    End Sub
End Class

The situation is like when we create roles, we will save who created this role. So i have a CreatedBy Property of type User. Similarly when we create a User, we will mention what role the new user belongs to .So i have a property called "Role" of type "Role". This circular reference giving me StackOverflow exception as its recursive when i create an object of User class.

How do i handle this ? should i restucture my entties ? how ?


Solution

  • Create constructor overloads in each of your classes to pass the host object:

    Public Class User
        Public Property UserID As Integer
        Public Property Role As Role
    
        Public Sub New()
            Me.Role = New Role(Me)
        End Sub
        Public Sub New(oRole As Role)
            Me.Role = Role
        End Sub
    End Class
    
    Public Class Role
        Public Property RoleID As Integer
        Public Property CreatedBy As User
    
        Sub New()
            Me.CreatedBy = New User(Me)
        End Sub
        Public Sub New(oUser As User)
            Me.CreatedBy = oUser
        End Sub
    End Class