When a string is created using the SubString() method, is the resulting string a copy of the elements of the original string (so there are now 2 memory locations with the same information) or is it a reference to the existing memory location?
If it is a copy, is there a way to make it a reference instead?
In C# strings are immutable* but not persistent. That means that new string that is result of SubString
method is not sharing common part with old string. Here is beautiful explanation from Eric Lippert.
* operation on string will return new string object
It's a copy, and you can't have a string
that's a reference to part of another string. A .net string isn't backed by an array, it contains the char data inline. i.e. it is a variable length class, similar to an array.
While that sub-reference model is a possible implementation (I think java strings are just slices into char arrays), it can lead to strange behavior, where keeping a small substring keeps the whole string in memory, a common pitfall with java substrings. I guess the .net designers wanted to avoid such issues.
You can use your own string like type that has this property. For example you could work on slices into a char array with ArraySegment<char>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With