Why was String designed as a reference type instead of value type?
From the modeling perspective I would have modeled it as a value type since it represents something without identity. It doesn't have distinguishing attributes. (E.g I can't make any difference between one string "a" and another string "a")
I know that I would have had serious performance problems having long strings stored on the stack. Probably it's impossible, as strings get very long, because stack is limited in size.
If it weren't for the performance why would you design System.String as a reference type? (Assume any possible string is at most 16 bytes long)
As you point out having a value type which may become very huge may be prohibitive due to limited stack space and the copy-on-use semantics of value types.
Also, the way strings are implemented in .NET adds a couple of elements to the equation. Strings are not only reference types, they are also immutable (outside the System namespace anyway) and the runtime uses interning to do neat tricks for strings.
All this adds up to a couple of benefits: Duplicate literal strings are only stored once and comparison of such strings becomes extremely effective as you can compare references instead of streams of Unicode characters. Those options would not be possible for value types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With