Brilliant. Very nice example.
So all of it's member must be const/readonly. And string might have internally implemented similiar pattern. Am I right ?
Printable View
Well, it could have non-const data within the class, but I think you get the point; the class does not expose a way for the outside world to change said data, and that data is guaranteed to not be changed during the lifetime of the object. The string class will have an internal char[] that contains the actual string data. Whenever you call a method that seems to change the string, you are actually getting a new (new String( data )) back in return.
An immutable class will simply not allow its state to be changed, period. This makes a class like that great for dealing with concurrency because you do not have to worry about intermediate states between writes and reads.
Thanks again.
So it's way clear now.
So every time, when a string provides an illusion to change it's data, it's actually creating a new string object internally. And the original data is unchanged.
After doing some research on this subject, I think it's an attempt to give a value type behavior to strings. Also as you told, it tries to provide const type behavior to strings, which is greatly helpful while using them in functions.
But I figure out one disadvantage:
Lets create an object to occupy 4 bytes say - A, B, C, D.
When I want another 'E', it is NOT expanding the current memory, but it simply forgets, and create a new memory in entirely new location.
So this is sort of an overhead.
(Let's don't jump into StringBuilder for now)
I believe there should be valid reasons, that are more critical comparing this overhead.
I think the reason to be to - Take the value type advantage. Am I right ?
If strings were mutable then every internal .NET function which returns a string would have to clone the string and return a copy. If you wrote a library, every place where you receive a user string and store it you'd have to clone it, every place you return a string to the user you'd have to clone it.
It'd become a giant source of bugs and issues.
The other thing is it's not possible to 'expand' a memory location as you suggest. If you want a 10 char string, you'd want .NET to allocate exactly 10 chars of space, otherwise you'd be wasting memory. So, what happens if you want to append a character? You have to get another memory location containing *11* chars of space, copy over the original 10 chars and append the new char. Essentially exactly what .NET does ;)
Of course, you could always hide this inside the string class, but as i said, it'd lead to a whole host of bugs and not give any performance benefits.