Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Substring(): Copy, or Reference?

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?

like image 206
3Pi Avatar asked Feb 01 '12 23:02

3Pi


2 Answers

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

like image 189
om-nom-nom Avatar answered Oct 20 '22 15:10

om-nom-nom


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>.

like image 38
CodesInChaos Avatar answered Oct 20 '22 13:10

CodesInChaos