Adding to list collection generates an error

RK62

Active member
Joined
Dec 29, 2010
Messages
33
Programming Experience
3-5
I'm trying to populate class properties where one property is a list collection. I get a NullReferenceException when trying to add to the list collection. The code (litlle bit simplified) is here:

VB.NET:
Public Class Portfolio

    Property Name As String    
    Property Assets As List(Of Asset) 

    Public Sub Populate(ByVal data As DataTable)

        For Each row As DataRow In data.Rows

            Dim asset As New Asset(CStr(row.Item("AssetName")))
            With asset
                .AssetID = CStr(row.Item("AssetNo"))
                .Value = CDec(CStr(row.Item("MarketValue")))
            End With

            Me.Assets.Add(asset)

        Next

    End Sub

Public Class Asset
 'properties here...
End Class

End Class

I have a nested class "Asset" inside the class "Portfolio"

Everything goes ok until the line
VB.NET:
Me.Assets.Add(asset)
Which gives me the NullReferenceException error.
Where's the problem?
 
You have declared a property by name Assets and type List(Of String), but never created a List object and assigned to the propertys backing store. To create an object use the New keyword.
 
Thanks for the quick reply. Changing the declaration to:
VB.NET:
Property Assets As New List(Of Asset)
will solve the problem.
 
Its
Private Assets as new List(of Assets)

Not
Property Assets as ...

if you need to reference it from a property you still need to declare it properly
then create a property structure that references the Assets declaration.

Hope this helps.
 
Its
Private Assets as new List(of Assets)

Not
Property Assets as ...

if you need to reference it from a property you still need to declare it properly
then create a property structure that references the Assets declaration.

Hope this helps.
That is not correct. VB 2010 now has auto-implemented properties. The full property body is only needed if additional code must be added to getter/setter. For auto-implemented properties the private backing field is generated.
 
Back
Top