7

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?

3 Answers 3

10

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.