Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any other reason beside performance and readiblity of why System.String is a reference type instead of value type?

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)

like image 224
Liviu Trifoi Avatar asked Jun 25 '10 07:06

Liviu Trifoi


1 Answers

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.

like image 163
Brian Rasmussen Avatar answered Oct 04 '22 07:10

Brian Rasmussen