How create a array of objects (another class) in VB.NET and initialise it. Since I am not sure about the length of the array, it should be generic. I mean I should be able to add any number of objects to the array. NB: I am much familiar with Generic List, but my client has given me array of objects :(
1 Answer
I should be able to add any number of objects to the array
Simply, you can’t, arrays aren’t resizable. You can use Array.Resize (or ReDim Preserve) but this will re-allocate the whole array and has abysmal runtime.
Use the list (List(Of T)) for your purpose. If you get the input in the form of an array, it’s a simple matter of transforming this input:
Dim lst As New List(Of YourObject)(inputArray)
Likewise for return values: if you need to return an array, use the ToArray() method of the list.
But using arrays in public interfaces (that is, as parameters and return values of public methods) is bad design and shouldn’t be done anyway. Talk to your client about this.
ArrayListfor that, one of the other classes found in theCollectionsnamespace.ReDimstatement for thisReDimis not an operator, it is a statement. And there are lots of important caveats to its usage, like you can only resize the last dimension of the array, which makes it quite inflexible for use with arrays with multiple dimensions. As well, that essentially re-creates the entire array (and if you specify thePreserveoption, copies the original items back into the newly-created array). It's quite an expensive operation, and not at all equivalent to the behavior you get with theCollectionclasses.