Android Question Passing String 'ByRef'

Alwinl

Member
Licensed User
Longtime User
I have read the tutorial on this and I have the understanding that primitives are passed by value and all others by reference, and that strings are not primitives. This is my code :

s1 = "abc"
SetVal(s1)
log(s1) 'I'd expect this to print 'xyz' but it prints 'abc'

sub SetVal(s2 as string)
s2 = "xyz"
end sub

So either a string is a primitive and is passed by value, or passing ByRef is not supported in this sense.
 
In this moment I can't try it, so may be that this don't work, but you can try with:

sub SetVal(ByRef s2 as string)
s2 = "xyz"
end sub

Sergio
 
Upvote 0
1. There is no ByRef in Basic4android.
2. Strings are immutable objects. You cannot modify an existing string object. What you are doing is you are assigning a new object to the variable. It will not have any effect on any other variables (assuming that it is a local variable).
You can pass a custom type that holds a string:
Code: Copy
Type StrRef (s As String)
This will allow you to pass the StrRef object and change its value.

You can also pass an array with a single string.

Last option is to pass a StringBuilder instead of String. Then you will be able to remove its current content and append the new content.
 
Upvote 0
Back
Top