Q on strings

H

HW

Hi, I understand strings are immutable in .NET CF so if i have the following
would it create a new string object each time?

Dim Tmp as String ' variable defined as member of class

tmp = func1(x) where func 1 returns a string
tmp = func1(y)
tmp = func1(z)

there is code inbetween these statements obviously. When tmp is assigned to
function would a new object be created?

How do i get round this if a new object is created?
 
S

Steve Maillet \(eMVP\)

Because strings are immutable they are also "interned" which means that if
you keep returning the exact same string there won't be a new object
creation. Also whether a new object is created or not in your example
depends entirely on what the function does. remember that tmp is not an
object instance but rather a reference to an object and the return from
func1 is a reference as well so you are not passing around an entire object.
It's possible that func1() could do things in a manner that does not
actually create a new string.
 
H

HW

thanks Steve, assuming the func1 returns a new different string each time
for each call
and is being assigned to tmp, then is tmp just refrenced to the new string
each time
or will a new copy of tmp be created each time. If tmp was char* as in C++
then you
can assign a new string to it each time but what will happen here with VB?
 
S

Steve Maillet \(eMVP\)

In the .NET framework "dim foo as string" is essentially like Cstring* foo =
new CString(); SO when you return a string from a function you are really
returning a reference. All object "variables" are really references to
object instances on the managed heap. so your temp variable and whatever
Func1() returns are just references to a string object on the heap so assign
the return value to temp is just like setting a pointer in C++

For class instances you get references to object instances on the managed
heap. (If you are familiar with c/c++ I'd recommend C# over VB. The syntax
will feel much more familiar to you. )
 

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