Dim and Initialize

stevel05

Expert
Licensed User
Longtime User
Just out of curiosity, and certainly not urgent, could anybody explain what Dim and Initialize do relative to B4A.

I understand that for views, initialize sets up a link to an event, and probably a lot more, but what about Lists etc.? And why do we have both?

Thanks

Steve
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
And why do we have both?
The reason is that there are cases where you do not need to initialize the object as you only want to hold another reference to an initialized object.
B4X:
Sub Buttons_Click
 Dim b As Button
 b = Sender
 b.Color = Colors.Red
End Sub
In this case Sender holds a reference to a button. If b was first initialized it was a large waste of resources.
 
Upvote 0

Eric H

Active Member
Licensed User
Longtime User
Sorry to activate an old thread, but I am still a bit confused on this issue. I tried searching for info related to vb about this, but wasn't able to find anything that really cleared it up for me. Part of the reason may be that I don't understand sender objects well enough to get much out of the code example. Can someone provide a more in depth explanation, or point me to a resource that can help me understand the differences and how to know when things should be initialized or not?

Thanks,
Eric H
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
If an object has an Initialize method then you need to call it before you "use" any of its other methods.

Two exceptions:
- Views added with the designer are initialized when the layout is loaded.
- This is not really an exception, however if you assign one variable to another then they both reference the same object:
B4X:
Dim sql1, sql2 As SQL
sql1.Initialize(...)
sql2 = sql1
sql2.Initialize <--  wrong, object was already initialized
 
Upvote 0

Eric H

Active Member
Licensed User
Longtime User
So Dim sets up a reference to an object/variable and tells the program to set aside a certain amount of memory that the object/variable value can be stored in. Like using the term 'shotgun' to claim the front passenger seat in a car before you are actually sitting there...

Initialize causes the actual object/variable data to actually be stored in the memory that has been set aside for it by the Dim statement. Like actually sitting in the car.

Does this sound right?

And if so, some things don't need to be initialized in code because the data for that reference is already actually stored/available in memory?

Thanks for helping me wrap my brain around this one Erel.
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…