Hmm.... let's explore this a little. I've worked with C for years, where
there are no such strings, but only arrays of characters. So my perspective
of reference types comes from a pretty good understanding of C and C++
pointers. Hwever, .Net is still something of a mystery to me when it comes to
the internal workings of the compiler and runtime engine.
First, strings are reference types, correct? And any time we type "..." in
the source code, this creates a static string that is compiled in to the data
section of our program (or some CLR analogue of this). Unlike integers or
floats, strings are reference types, meaning that the variable doesn't hold
the value of our data, but rather holds the LOCATION of our data.
If I assign something to a string variable, like this:
A="Test1"
and later: A="Test2"
It's my impression that what you're actually doing is re-assigning the
reference variable "A" to point to the static string "Test1" or "Test2". If
we later said 'B=A', we would be setting B's reference to the same address as
A's reference.
Now, if we "modify" A, like this:
A=A & "Test3"
A now points to a string that has the value "Test2Test3", and B still points
to a string that has the value "Test2".
This is why, to make multiple references to a string, we'd need a wrapper
class. Then we can happily say this:
dim A as New WrapperClass
dim B as WrapperClass
A.Text="test1"
B=A
A.Text="Test2"
B.Text will now be Test2.
Does this make sense?
"Jon Skeet [C# MVP]" wrote:
Tom Wilson <To*******@discussions.microsoft.com> wrote: Simply put: you can't with just the string type. When you modify a string in
.Net, I believe that the original string is *copied* to the new string,
complete with your changes.
No, you just can't modify a string.
This means that the string reference changes when you change your string.
You can't change the string. You can change the value of your string
reference to a new one with text based on the first one:
tmp = tmp.Replace("a", "b");