6

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?

H.B.
  • 166,899
  • 29
  • 327
  • 400
3Pi
  • 1,814
  • 3
  • 19
  • 30

3 Answers3

9

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

Community
  • 1
  • 1
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
7

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

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
0

It's a new string. You could knock something up that say kept start and end positions of some other string, eg, the arguments you would send to substring if you called it. If it was a fixed pattern (or at least could be fixed for a known interval, you could chop it up in advance, or use StringBuilder, or a Stream with TextReader.

I'd say if substring is an issue in a llanguage with immutable strings, you should design out the need for it. It's handy but it should be a one off.

Tony Hopkinson
  • 20,172
  • 3
  • 31
  • 39