'Does using a Range to get part of a string create a new string in memory?
By using the C# 8 feature Range, does it create a new string in memory or does it provide a "pointer" to the memory parts of the previous string already there?
Solution 1:[1]
var x = "foo"[1..2];
Is compiled to;
int num = 1;
int length = 2 - num;
"foo".Substring(num, length);
And .Substring will create a new copy of the characters.
If you don't need a string, you could use "foo".AsSpan()[1..2];
Solution 2:[2]
I'm not following your question. A range of a string is not a string, its an array of char. string implements IEnumerable<char>.
If you want a substring, then you should use string.Substring, and yes, it will create a new string.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeremy Lakeman |
| Solution 2 | marc_s |
