Skip to main content

Posts

Showing posts with the label Immutable String

Why and how the C# strings are immutable? Explained with examples

C# strings are immutable, meaning that once a string object is created, its value cannot be changed. Instead, any operation that modifies a string, such as concatenation or replacement, creates a new string object with the modified value. One reason for this immutability is that strings are often used as keys in dictionaries or as elements in collections, and immutable objects are more efficient for these uses because their hash code does not change. Another reason is that strings are often used in multithreaded environments, and immutability allows multiple threads to access the same string object without the risk of data corruption.  Example: The string which is a reference type stored in a memory heap Suppose we are creating a string str and assign a value  "a"; That will be stored in the memory location like this Again if we assigning another value to the same string that is "b"  This will not replace the existing value Instead this will create another memory