How to access array elements of a VBScript class property (returning an array)

To my surprise it doesn’t seem possible to access array elements when directly referencing a class property in VBScript.

This means you cannot do this:


class ArrayClass

	private m_myArray

	public property get MyArray()
		MyArray = m_myArray
	end property

end class

Dim arrayClass : set arrayClass = new ArrayClass

Response.Write(arrayClass.MyArray(0))

' Will yield an error ala:

' Microsoft VBScript runtime error '800a01c2'

' Wrong number of arguments or invalid property assignment: 'MyArray'

Strangely enough it is possible to access the array elements from within the class itself, so this is how I solved it (thanks to 4 Guys From Rolla):

Create an intermediate property getter which accesses the array on index as such


class ArrayClass

	private m_myArray

	public property get MyArray()
		MyArray = m_myArray
	end property

	public property get MyArrayValue(pos)
		'Make sure the end developer is not requesting an
		'"out of bounds" array element
		if pos < LBound(m_myArray) or pos > UBound(m_myArray) then
			exit property    'Invalid range
		end if

		MyArrayValue = m_myArray(pos)
	end property
end class

' Then you can access the array elements like so:

Dim arrayClass : set arrayClass = new ArrayClass

Response.Write(arrayClass.MyArrayValue(0))

I’m not a VBScript expert so if anyone can explain why this is happening it would be great!

This entry was posted in VBScript and tagged , , , , , . Bookmark the permalink.