Sharing an instance of an object across classes

B

Beth

OK, Cor, pardon my considerable ignorance, but I thought the whole question
was what is the value of 'a' AFTER myMethod is called.

If you have:
dim a = "Michel"
myMethod(a)
msgbox("a is " & a)

and myMethod is:
Private Sub myMethod(byVal a as string)
a = "Beth"

then the message says 'a is Michel'. If 'a' is passed byRef, the message
says 'a is Beth'. When 'a' is passed byVal, then a second copy of 'a' is
created in memory, instead of a pointer to the existing variable declared by
the caller when it's passed byRef.

Both variables would be marked (or whatever) for garbage collection when
they fell out of scope, although the ByRef variable can't be marked as trash
when it falls out of scope in myMethod because the caller still has a
reference to it, so it will fall out of scope within the calling routine.
The 'a' passed byVal will fall out of scope within myMethod, along with all
the other variables declared in myMethod.

So you use byVal when you want the variable to remain immutable (unchanged,
or not mutating,) and byRef when you want the variable used as an output
parameter.
But I think you know that, so when you say:
ByRef is for when the referenced object is immutable

you're referring to the pointer being immutable, not the value. Although I
thought pointers were always immutable, and it was just a question of whether
or not another one gets created.

That's my understanding, anyways, but if I'm off somewhere, feel free to let
me know.

Thanks again for your response,

-Beth
 
C

Cor Ligthert[MVP]

The object is immutable, everytime a simple change is made in a string, a
new string is created with in fact a new reference.

That is the reason that changing a string can cost more in time and memory
than a string builder.

You are mixing up the ByVal and the ByRef from the time there were no
objects.

Cor
 
B

Beth

OK, I thought when you said 'referenced object,' you were referring to an
instance of a class, not any variable in memory.

I could very well be mixing up the byVal/byRef functions from when there
were no objects, I just know if I want an output parameter, for a string or
not, I need to use byRef instead of byVal.

So your 'immutable' comment threw me, but that's ok. There's a bunch of
stuff going on under the hood I try to remain blissfully ignorant about.

Thanks again for your replies,

-Beth
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top