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?


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];

Answered By – Jeremy Lakeman

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.