Larry Fogli Larry Fogli -4 years ago 74
Vb.net Question

How can I add a list of objects to a class

I have been working on this problem for a few days now and I'm struggling with it. What I am trying to achieve is to have a list of a class in another class.

Code:

Public Class Account
Public Property Email() As String
Get
Return m_Email
End Get
Set(ByVal value As String)
m_Email = Value
End Set
End Property
Private m_Email As String
Public Property Active() As Boolean
Get
Return m_Active
End Get
Set(ByVal value As Boolean)
m_Active = Value
End Set
End Property
Private m_Active As Boolean
Public Property CreatedDate() As DateTime
Get
Return m_CreatedDate
End Get
Set(ByVal value As DateTime)
m_CreatedDate = Value
End Set
End Property
Private m_CreatedDate As DateTime
End Class

Public Class ListOfAccounts
Public Property User() As String
Get
Return m_User
End Get
Set(ByVal value As String)
m_User = value
End Set
End Property
Private m_User As String
Public Property Accounts() As List(Of Account)
Get
Return m_Accounts
End Get
Set(ByVal value As List(Of Account))
m_Accounts = value
End Set
End Property
Private m_Accounts As List(Of Account)
End Class


Instead the code for populate is:

Dim Naccount As New ListOfAccounts
Naccount.User = "James"
For i = 0 To 5
Dim AccountL As New Account
AccountL.Active = True
AccountL.CreatedDate = Now
AccountL.Email = "james" & i.ToString & "@example.com"
Naccount.Accounts.Add(AccountL)
Next


I am getting a
NullReferenceExceptio
n on the last line of this code.

Answer Source

Naccount.Accounts itself isn't a List you can add to, it's a property you can assign a List to.

m_Accounts is a List you can add to but it's private and not yet instantiated (created).

Try this example which might help you solve your problem:

Dim Naccount As New ListOfAccounts
Naccount.User = "Luke"
Dim AccountList As New List(Of Account)
For i = 0 To 5
    Dim AccountL As New Account
    AccountL.Active = True
    AccountL.CreatedDate = Now
    AccountL.Email = "Luke" & i.ToString & "@gmail.com"
    AccountList.Add(AccountL)
Next
Naccount.Accounts = AccountList
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download