Suppose i have this class:
class Foo
Public Property a() As Integer
Private _l As List(Of Integer) = New List(Of Integer)
Public Property l() As List(Of Integer)
Get
Return _l
End Get
Set(value As List(Of Integer))
_l = value
End Set
End Property
end class
I am trying to use initializer list to initialize the properties:
Dim f as Foo = New Foo With {.a = 1, .l.Add(1)}
The above doesn’t work. I am getting a bit confused here. Now, in an initializer list from what i understand, i can initialize the collection like this:
Dim f as Foo = New Foo With {.a = 1, .l = New List(Of Integer){1}}
But what i need to do, since _l is already pointing to an object when i say New Foo, is only add the elements without saying ..., .l = New List(Of Integer){1}}. Why isn’t it working?
It’s possible using collection initializer syntax, i.e.
Dim f As New Foo From {1, 2, 3}(see below). However, this has a few drawbacks:With {.a = 1}) at the same time. Thus, you’ll have to move initialization of propertyato a constructor.IEnumerableand have anAddmethod.That said, here is a working example:
And it can be used as follows: