Answered by:
Separate list of objects

Question
-
User-2089506584 posted
Hello,
Why I couldn't have a separate list of objects of the same class?
This one works,
Dim list As New List(Of Address)
list.Add(New Address With { _
.Country = "USA", _
.State = "New York" _
})
Return list.ToList
not, [:(]
Dim list As New List(Of Address)
list.Add(New Address With { _
.Country = "USA" _
})
list.Add(New Address With { _
.State = "New York" _
})
Return list.ToListI'm getting "Object reference not set to an instance of an object."
-imperialx
Wednesday, April 21, 2010 6:22 AM
Answers
-
User-952121411 posted
Yes I think you need to show some details about at least those (2) properties on the 'Address' class because the syntax you provide does indeed work. Take a look at my code below for a Customer class. I get no issues as you have:
Dim MyCustomer As New List(Of Customer) MyCustomer.Add(New Customer With { _ .FirstName = "John"}) MyCustomer.Add(New Customer With { _ .LastName = "Smith"})
Now since the 'New' keyword was used, it creates (2) separate instances and adds them to the list. If for some reason you wanted to add the property values at different times to the same instance, you would have to reference it by .Item index. For the code above though, here is the output:?MyCustomer.Item(0)
{MyApp.Customer}
FirstName: "John"
ID: 0
LastName: ""
mFirstName: "John"
mID: 0
mLastName: ""
?MyCustomer.Item(1)
{MyApp.Customer}
FirstName: ""
ID: 0
LastName: "Smith"
mFirstName: ""
mID: 0
mLastName: "Smith"
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, April 21, 2010 10:14 AM
All replies
-
User191633014 posted
in second case you add 2 Address classes:
First with set Country, second with set State.
Wednesday, April 21, 2010 6:39 AM -
User614805505 posted
Dear imperialx,
Can show ur Address class?
Wednesday, April 21, 2010 6:42 AM -
User-952121411 posted
Yes I think you need to show some details about at least those (2) properties on the 'Address' class because the syntax you provide does indeed work. Take a look at my code below for a Customer class. I get no issues as you have:
Dim MyCustomer As New List(Of Customer) MyCustomer.Add(New Customer With { _ .FirstName = "John"}) MyCustomer.Add(New Customer With { _ .LastName = "Smith"})
Now since the 'New' keyword was used, it creates (2) separate instances and adds them to the list. If for some reason you wanted to add the property values at different times to the same instance, you would have to reference it by .Item index. For the code above though, here is the output:?MyCustomer.Item(0)
{MyApp.Customer}
FirstName: "John"
ID: 0
LastName: ""
mFirstName: "John"
mID: 0
mLastName: ""
?MyCustomer.Item(1)
{MyApp.Customer}
FirstName: ""
ID: 0
LastName: "Smith"
mFirstName: ""
mID: 0
mLastName: "Smith"
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, April 21, 2010 10:14 AM