KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
A few weeks ago, I discovered that strings in C# are defined as reference types and not value types. Initially I was confused about this, but then after some reading, I suddenly understood why it is important to store strings on the heap and not the stack - because it would be very inefficient to have a very large string that gets copied over an unpredictable number of stack frames. I completely accept this. I feel that my understanding is almost complete, but there is one element that I am missing - what language feature do strings use to keep them immutable? To illustrate with a code example: string valueA = "FirstValue"; string valueB = valueA; valueA = "AnotherValue"; Assert.AreEqual("FirstValue", valueB); // Passes I do not understand what language feature makes a copy of valueA when I assign it to valueB. Or perhaps, the reference to valueA does not change when I assign it to valueB, only valueA gets a new reference to itself when I set the string. As this is an instance type, I do not understand why this works. I understand that you can overload, for example, the == and != operators, but I cannot seem to find any documentation on overloading the = operators. What is the explanation?
Tags (comma-separated)
Save Edits
Cancel