Scope of Initialize Parameters

Penko

Active Member
Licensed User
Longtime User
Hello again.

Classes are pretty good, it's just time that I need to start using them properly.

A past habit of mine(from VB.NET) is to name Public Properties with the same variables as input parameters. This is exactly what I did here and it did the second trick for this evening to me. Here is the demonstration:

B4X:
Sub Button3_Click

   Dim test As TestClass
   test.Initialize(0, "test")
   
   Msgbox(test.Param2, "msg")
   
End Sub

B4X:
'Class module
Sub Class_Globals
   
   Private P_param1 As Int
   Private P_param2 As String
   
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize (Param1 As Int, Param2 As String)

   P_param1 = Param1
   P_param2 = Param2

End Sub

Public Sub Param1 ' rename to PropertyParam1 to get it working
   Return P_param1
End Sub

Public Sub Param2
   Return P_param2
End Sub

This should work pretty good in VB.NET as Param1, Param2 are used as parameters in Initialize. However, it seems this is an issue in B4A which took me another 1,5 hours to investigate. The exact problem is that whatever you try, all parameters are Null even if you Log them immediately after calling Initialize.

My question is - is this on purpose or it is a bug? If it is the first, Erel, you may be willing to add it as a compile problem because it's not visible at the very first glance.
 
Last edited:

margret

Well-Known Member
Licensed User
Longtime User
Your variable names used in the init are commands to call the subs. You need to rename your subs to param_1 and param_2 and it will work just fine. It may be the compiler should know the difference but I understand why it is doing what it is doing. When it sees p_param1 = param1, that is what calls the sub, the code says p_param1 = the subs returned value. When you log right after the init, the subs returned value is nothing because it has no assigned value.
 
Last edited:
Upvote 0

Penko

Active Member
Licensed User
Longtime User
Seems legit! I haven't thought it that way. In .NET the subs are explicitly defined as properties and maybe that saves the situation. I have already renamed them but this trigerred my interest. Thanks for the detailed reply which made me understand where I am missing the obvious.

Sent from my HTC Desire using Tapatalk
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…