views:

79

answers:

4

This is related to my previous question but it is a different problem.

I have two classes: Server and Database.

Public Class Server

Private _name As String
Public Property Name() As String
    Get
        Return _name
    End Get
    Set(ByVal value As String)
        _name = value
    End Set
End Property


Private _databases As List(Of Database)
Public Property Databases() As List(Of Database)
    Get
        Return _databases
    End Get
    Set(ByVal value As List(Of Database))
        _databases = value
    End Set
End Property


Public Sub LoadTables()
    Dim db As New Database(Me)
    db.Name = "test"

    Databases.Add(db)

End Sub
End Class

Public Class Database
Private _server As Server

Private _name As String
Public Property Name() As String
    Get
        Return _name
    End Get
    Set(ByVal value As String)
        _name = value
    End Set
End Property


Public Property Server() As Server
    Get
        Return _server
    End Get
    Set(ByVal value As Server)
        _server = value
    End Set
End Property


Public Sub New(ByVal ser As Server)
    Server = ser
End Sub
End Class

Fairly simple. I use like this:

Dim s As New Server
    s.Name = "Test"
    s.LoadTables()

The problem is in the LoadTables in the Server class. When it hits Databases.Add(db) it gives me a NullReference error (Object reference not set). I don't understand how it is getting that, all the objects are set. Any ideas? Thanks.

+4  A: 

You haven't actually created the list that you are attempting to add the object to. You've only created the property and it's backing property. You need to instantiate the list and assign it, typically in the constructor, or as part of the declaration.

Public Sub New()
   Databases = New List(Of Database)
End Sub
tvanfosson
+4  A: 

Databases is null.

Change it to

Private _databases As New List(Of Database)
SLaks
+1 for example code
Adam Driscoll
+2  A: 

I can't see where the _databases private field is being initiated, as it stands it is a null pointer.

Otávio Décio
+2  A: 

Take a close look at the code for the Databases property

Private _databases As List(Of Database)
Public Property Databases() As List(Of Database)
    Get
        Return _databases
    End Get
    Set(ByVal value As List(Of Database))
        _databases = value
    End Set
End Property

The getter here simply returns the field _databases. This field is defined but never initialized hence it is Null/Nothing. Try changing the field to

Private _databases As New List(Of Database)
JaredPar