Reputation: 623
I would like to know if its possible to write multiple lines, the equivalent of this line bellow, but instead of using With and From use multiple lines to declare data.
Dim Price = New PriceStruc() With { _
.Bids = New List(Of Prices)() From {New Prices() With {.Price = 1101, .Size = 1}},
.Offers = New List(Of Prices)() From {New Prices() With {.Price = 1102, .Size = 1}}}
Upvotes: 1
Views: 66
Reputation: 38865
You can add parameters to the constructor to set properties when you create an instance. This is especially helpful for an object which should only exist when this or that property is known. Another use in designer serialization, among others.
Warning: taking it as far as requested doesnt make the code any easier to read
I dont know exactly what these are, so I made up my own and fixed some of the nomenclature (it looks like Prices
has data for one item, yet it is plural).
Friend Class Price
Public Property Value As Integer
Public Property Size As Integer
Public Sub New()
End Sub
Public Sub New(v As Integer, s As Integer)
Value = v
Size = s
End Sub
End Class
The simple constructor (no params) is there because many serializers require one. Depending on the serializer, you can it set it as Friend
to force your code to use the overload and specify Value
and Size
when you create an new Price object. This is useful when an object has no right being created without certain key information. (You can still use it in For Each
loops because you do not need a new object for that).
In this case, the Value
(named to avoid Price.Price
) and Size
might be required elements, but the constructor overload is mainly a convenience. To use it:
Dim p As New Price(1101, 1)
Now, those objects can be instanced without With
. The holder looks like this:
Friend Class PriceItem
Public Property Bids As List(Of Price)
Public Property Offers As List(Of Price)
Public Sub New()
End Sub
Public Sub New(b As List(Of Price), o As List(Of Price))
Bids = b
Offers = o
End Sub
End Class
There is likely more to it, like a Name
indicating what the Bids and Offers are for, but the idea is the same: pass the lists in the constructor.
Now you can initialize the Price
objects and PriceItem
using their constructors:
Dim Prices = New PriceItem(New List(Of Price)(New Price() {New Price(1101, 1),
New Price(1102, 1)}),
New List(Of Price)(New Price() {New Price(1106, 7),
New Price(1104, 1)}))
1101 and 1102 are the Bid items, 1106 and 1104 are the offer items.
As I said, it doesnt make it any easier to read, debug or code. It perhaps makes sense for a Price
item but passing lists to the PriceItem
ctor seems a bit much. Rather than trying to squeeze everything into the initialization, this seems to strike the best balance between readability and conciseness:
Dim PItem As New PriceItem
PItem.Bids = New List(Of Price)(New Price() {New Price(1101, 1), New Price(1102, 1)})
PItem.Offers = New List(Of Price)(New Price() {New Price(1106, 7), New Price(1104, 1)})
Upvotes: 2