I have a property which is an array of items, but when I come to add an item to the array it says I must use the new keyword, but I can’t use a new keyword with a property.
(item is a custom class.)
Private itemsvalue As item()
Public Property Items() As item()
Get
Return itemsvalue
End Get
Set(ByVal value As DBPFindexitem())
itemsvalue = value
End Set
End Property
Sub New(ByVal indexbytes As Byte(), ByVal number as integer)
For count As Integer = 0 To number
Dim offset As Integer = count * 2 * 4
Dim xx As New item
xx.Group = BitConverter.ToInt32(indexbytes, offset + 0)
xx.ID = BitConverter.ToInt32(indexbytes, offset + 8)
Items(count) = xx
Next
End Sub
How can I add the xx item to the array of items?
You should be using a collection instead of an array.
A Collection will automatically resize to hold as many items as you put into it.
For example:
If you’re writing a public library, you should use a
System.Collections.ObjectModel.Collection(Of item)instead. This will allow you to replace it later with an inherited collection with special behavior, without breaking existing clients. See here.If you don’t want other people to modify the collection, you should expose a
System.Collections.ObjectModel.ReadOnlyCollection(Of item).If you really want to use an array, you should initialize the array, like this: