Question

I have defined a structure in VB.NET and created an array from it:

Public Struct MyStruct
    Dim SomeValue As String
    Dim SomeOtherValue As Double
End Struct

Public MyArr() As MyStruct

I am wondering if there is no .push_back function available for the array under VB.NET as it would be in C++.

Currently I am redimming + preserving the array and assign a new array member to the new empty member which is quite typing-intensive and which is not so cool in aspects of a readability:

 Redim Preserve MyArr(0 To MyArr.GetUpperbound(0) +1)
 MyArr(MyArr.GetUpperbound(0)) = someNewItem

Thank you for the help!

Was it helpful?

Solution

This is what I meant:

Dim lst As New List(Of MyStruct)
lst.Add(someNewItem)

Assuming you have declared this:

Public Structure MyStruct
  Dim SomeValue As String
  Dim SomeOtherValue As Double
End Structure

If you absolutely need to be working with arrays, try this:

MyArr = MyArr.Union({someNewItem}).ToArray

OTHER TIPS

Structs are mainly used for performance, but as you are using Redim Preserve that is obviously not the reason in your case.

Unless you have a specific reason to use a struct, you should use a class instead, and use a list instead of an array:

Public Class MyClass

  Dim SomeValue As String
  Dim SomeOtherValue As Double

  Public Sub MyClass(value As String, other As Double)
    SomeValue = value
    SomeOtherValue = other
  End Sub

End Struct

Public MyList As New List(Of MyClass)

Now you can easily add items to the list:

MyList.Add(New MyClass("Answer", 42))

The C++ Standard Template Library vector class provides a push_back method. A C++ vector encapsulates a resizeable array.

As pointed out by @Neolisk, the .Net equivalent of a generic resizeable array is a List Of T (the non-generic version is the more aptly named ArrayList).

You can use a struct with a List of T, there is no need to define a class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top