Android Question Re-Dim globals to avoid List multiple instances?

Arf

Well-Known Member
Licensed User
Longtime User
I know that I need to re-dim anything I put in lists before adding them again, but I have a global variable I want to put in a list, multiple times without it overwriting the previous list items of itself.

can one re-Dim a global variable anywhere in the code and achieve this goal?
If not, as I suspect, is there no other way of 'isolating' a list item from the object that it references?
 

Troberg

Well-Known Member
Licensed User
Longtime User
It's easier to understand if you don't think of the variable as the content of the variable. The content is stored somewhere, and the variable holds the location of that storage. Another variable might also hold that location, and if one of them changes the contents, both will see the change. Likewise, if you destroy one of the variables, the other will remain, and so will the contents. It's not until you destroy the last variable that holds that location that the contents themselves will be destroyed.

Example:

B4X:
Dim A as MyClass
A.Text="A"
Dim B as MyClass
B.Text="B"
Log(A.Text) 'A 'They are now two different objects with different contents
Log(B.Text) 'B
B=A 'Now, both points to the object that was first created by A, and the object that was created by B is destroyed
Log(A.Text) 'A
Log(B.Text) 'A
A.Text="B" 'Both points to the same object, so both instances will change
Log(A.Text) 'B
Log(B.Text) 'B
Dim A as MyClass
A.Text="X" 'Now, they are are different objects, so the change wil only affect one of them
Log(A.Text) 'X
Log(B.Text) 'B 'Since B still holds a reference to the object created by A, it will still log B
A.Text="B"
Log(A.Text) 'B 'Now, both log B, but they are different objects
Log(B.Text) 'B
A.Text="A"
Log(A.Text) 'A 'As they were different objects, a change to one of them does not affect the other
Log(B.Text) 'B

This might be a bit messy for a beginner, but once you start thinking about it as the variable holding a location of the content, and not the content itself, it's not that hard.
 
  • Like
Reactions: Arf
Upvote 0

Arf

Well-Known Member
Licensed User
Longtime User
Thank you - that makes perfect sense.
Coming from embedded C and C++ I really struggled with the idea that I could not use pointers.. now I understand why. They're all pointers already! Kind of.
 
Upvote 0

Troberg

Well-Known Member
Licensed User
Longtime User
If you are familiar with pointers, you'll have no troubles as all.

One small note, though: All I wrote assumes that you use objects. Primitive types (string, int, boolean et cetera) does not work that way, they store their values directly in the variable.
 
  • Like
Reactions: Arf
Upvote 0
Top