Making Reusable Code

What is the best way to pass a for each loop into a method? I want to pass in an array to loop through and the data type for the array. The problem I am having with this is I also want to use a custom variable from that array item, for example:

Dim Rects() As REALbasic.Rect
Rects.Append New REALbasic.Rect
Rects.Append New REALbasic.Rect
Rects.Append New REALbasic.Rect
IncreaseByOne(Rects, REALbasic.Rect.Left) //pass the rects array and the variable for each array item's Left to be increased by 1


Dim Controls() As RectControl
Rects.Append button1
Rects.Append htmlviewer1
Rects.Append textfield1
IncreaseByOne(Controls, RectControl.Top) //pass the controls array and the variable for each array item's Top to be increased by 1


Sub IncreaseByOne(Arr() As Object, ByRef Var As Variable)
  For Each Item As Object In Arr
    Item.Var = Item.Var + 1 //I made up the "Variable" data type which allows you to predefine the variable to increase by 1 without writing the for loop outside the method
End Sub

Thanks for any help given.

There are some fundamental issues with what you are trying to do. I understand your intent, but unfortunately since the implementation of IncreaseByOne you have provided receives an array of Object, the compiler won’t have any notion of what properties may be available, and will throw errors.

Knowing a little more about the context in which you wish to use this would help. Will you always be passing in an array of objects that are subclasses of RectControl? If they are all descendents of a common class, you can declare the array to be of the common ancestor type and then use some select…case statements to get close to what you want.

For example, if everything you want to pass to this method descends from RectControl, they’ll all have the RectControl properties. As such, you can implement the method like this:

Sub IncreaseByOne(Arr() as RectControl, prop as String)
    for each item as RectControl in Arr
        select case prop
        case "Top"
    = + 1
        case "Left"
            item.left = item.left + 1

Note that I have not actually tried to compile this - but it should work.

One other thought, if everything you are planning to use in this context does inherit from some common ancestor, you could conceivably put in your own child class that implements methods like shiftLeft(), shiftUp(), shiftDown(), etc.

This is harder (maybe not even possible) if you are using all the built-in UI widgets that Xojo provides, as I don’t think you can change their base classes… but if you are developing your own set of classes for something, you could.

At any rate, more info from you would be helpful to give you better direction.