simple question

  • Thread starter Thread starter Carly
  • Start date Start date
C

Carly

Hi there,

I know that string is a reference type.

I have the following code:

Dim s As String
Dim s2 As String
s = "AAAAA"
s2 = s
MsgBox(s2)
s = "BBBBB"
MsgBox(s2)

I am not sure I understand why the second MSGBOX still shows "AAAAA"
since the two strings point to the same memory location.

Please help.

Carly
 
Visual Basic treats strings as a special case among the reference types.
The statement "s2 = s" makes a distinct immutable copy of the original string.
 
Thank you Tim

Tim said:
Visual Basic treats strings as a special case among the reference types.
The statement "s2 = s" makes a distinct immutable copy of the original string.
 
I thought when you do this:

Dim s as String
Dim s2 as String
s = "abcde"
s2 = s
Console.WriteLine(s is s2) --> True

that the compiler sets s2 and s to point to the same place in
memory, and it's only when you assign something different to one
of them that a new reference to a different string in memory
is created.

And in fact, if you set two strings to the same value, like this:

s = "abcdefgh"
s2 = "abcd" & "efgh"
Console.WriteLine(s is s2) --> True

I thought that the compiler will recognize that they are the
same and allocate only one block of memory for the string,
with the two variables pointing to it.

Did I learn something incorrectly?

Thanks,
Robin S.
--------------------------
 
I thought when you do this:

Dim s as String
Dim s2 as String
s = "abcde"
s2 = s
Console.WriteLine(s is s2) --> True

that the compiler sets s2 and s to point to the same place in
memory, and it's only when you assign something different to one
of them that a new reference to a different string in memory
is created.

And in fact, if you set two strings to the same value, like this:

s = "abcdefgh"
s2 = "abcd" & "efgh"
Console.WriteLine(s is s2) --> True

I thought that the compiler will recognize that they are the
same and allocate only one block of memory for the string,
with the two variables pointing to it.

Did I learn something incorrectly?

Thanks,
Robin S.

Robin,

You are correct - it's called interning. The runtime treats strings
differently then other reference types. Basically, the compiler builds a
table of all the litteral strings in your app and then the runtime will reuse
those addresses rather then allocate new string space each time.
 
Tom Shelton said:
Robin,

You are correct - it's called interning. The runtime treats strings
differently then other reference types. Basically, the compiler builds a
table of all the litteral strings in your app and then the runtime will
reuse
those addresses rather then allocate new string space each time.

Thanks. It's nice to know I can remember something that I think
is sort of obscure. :-)

Robin S.
 
Back
Top