microsoft / referencesource

Source from the Microsoft .NET Reference Source that represent a subset of the .NET Framework
https://referencesource.microsoft.com/
MIT License
3.13k stars 1.26k forks source link

Why `Substring` cannot make a reference to the original data instead of a copy? #181

Open jjxtra opened 1 year ago

jjxtra commented 1 year ago

https://github.com/microsoft/referencesource/blob/dae14279dd0672adead5de00ac8f117dcf74c184/mscorlib/system/string.cs#L1302

Why can't Substring just have a reference to the original unmanaged memory? Is there something with GC that would prevent a string referencing another string?

svick commented 1 year ago

This repo is not very active, so it's not a great place to ask questions like this. A better choice would be the repo for the modern .Net runtime: dotnet/runtime.

That being said, what you're saying would require changing the structure of the string type, which is a pretty fundamental part of the runtime. Instead, .Net decided to add the Span<T> type, which can represent any memory sequence, which means the equivalent operation to Substring, called Slice, works exactly the way you want there.