Passing a Reference to a String in C#

  • Thread starter Thread starter Drakkith
  • Start date Start date
  • Tags Tags
    Reference String
  • #31
pbuk said:
Yes that's right.

It's probably also worth mentioning that strings in C# are immutable: it is not possible to change their state. If you want to pass something to a function that modifies it then you can use the StringBuilder class.
Thanks, pbuk. I got around whatever limitation kept me from passing the reference to the original string around by creating my own class.
 
on Phys.org
  • #32
pbuk said:
strings in C# are immutable
Drakkith said:
limitation kept me from passing the reference to the original string

When you tried to change the "original string" somewhere else you didn't actually change it. you created a new string then assigned it to the "other" variable. The "original" happily hung out and was used for the tooltip.

BoB
 
  • Like
Likes   Reactions: harborsparrow and Drakkith
  • #33
rbelli1 said:
When you tried to change the "original string" somewhere else you didn't actually change it. you created a new string then assigned it to the "other" variable. The "original" happily hung out and was used for the tooltip.

BoB
Well that answers that. Thank you!
 
  • #34
Oh I'm an idiot. From my own link in post #26:

Because a string "modification" is actually a new string creation, you must use caution when you create references to strings. If you create a reference to a string, and then "modify" the original string, the reference will continue to point to the original object instead of the new object that was created when the string was modified.

The explanation was right in front of me as soon as I found that page and I just missed it completely.
 
  • #35
Drakkith said:
The explanation was right in front of me as soon as I found that page and I just missed it completely.
Sounds familiar... <wry smile emoji>
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
Replies
4
Views
4K
  • · Replies 6 ·
Replies
6
Views
4K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 17 ·
Replies
17
Views
3K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 11 ·
Replies
11
Views
4K
  • · Replies 9 ·
Replies
9
Views
4K