Question Dynamic type of structure?

przerull

New member
Joined
Jun 7, 2008
Messages
1
Programming Experience
1-3
Hi everyone. Impressive forum.

Now I do believe that vb is statically typed but might there be a way for me to get around this problem. I have a structure called easyarray. I just wanted a data structure that could be easily worked with that could emulate an array but with adding and removing elements with a brevity of code and without explicitly redimming. I need to work the icloneable for it but that's easy.

I need this structure to have a constructor perhaps that takes a type as an argument and then sets the underlying array _var to be of that type.

Here's the code:
VB.NET:
Public Structure easyarray
	Private _val() As String
	
	Default Public Property item(index As Integer) as String
		Get
			return _val(index)
		End Get
		Set(ByVal value As String)
			_val(index) = value
		End Set
	End Property
	
	Public Sub add(value As String)
		Try
			ReDim Preserve _val(ubound(_val) + 1)
		Catch
			redim preserve _val(0)
		End Try
		_val(ubound(_val)) = value
	End Sub
	Public Function count As Integer
		return ubound(_val)
	End Function
	
	Public Sub remove(index As Integer)
		dim temp as string = _val(ubound(_val))
		ReDim Preserve _val(ubound(_val) - 1)
		For i As Integer = 1 To ubound(_val) - index
			_val(index + i - 1) = _val(index + i)
		Next
		_val(ubound(_val)) = temp
	End Sub
	
	Public Sub InsertAfter(index As Integer, value as String)
		ReDim Preserve _val(ubound(_val) + 1)
		For i As Integer = 0 To ubound(_val) - index
			_val(ubound(_val) - i ) = _val(ubound(_val) - i - 1)
		Next
		_val(index) = value
		
	End Sub
	
End structure
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,468
Location
Norway
Programming Experience
10+
that could emulate an array but with adding and removing elements with a brevity of code and without explicitly redimming.
That is called a collection.
I need this structure to have a constructor perhaps that takes a type as an argument and then sets the underlying array _var to be of that type.
That is what generics are for.

Try the List(Of T) where T is the type. A sample:
VB.NET:
Dim labels As New List(Of Label)
Dim l As New Label
labels.Add(l)
labels(0).Text = "label text"
labels.Remove(l)
 
Top Bottom