C# - Prove that string is immutable
In C#, strings are indeed immutable. Let's prove this by examining some key aspects of string manipulation in C#.
1. String Creation:
In C#, when you create a string, it cannot be modified after it's created. Strings are instances of the System.String
class. Here's how you create a string:
string originalString = "Hello, world!";
2. Concatenation:
If you want to concatenate strings, the operation does not modify the original
string. Instead, it creates a new string that represents the concatenated result:
string newString = originalString + " Welcome!";
In this example, originalString
remains unchanged, and newString
contains the concatenated result.
3. Substring:
If you extract a substring from an existing string, it also results in a new string, leaving the original string unaltered:
string subString = originalString.Substring(0, 5); // "Hello"
Here, subString
is a new string that contains "Hello," but originalString
is still "Hello, world!".
4. String Methods:
Methods that appear to modify a string actually return a new string with the desired changes. For instance, if you want to make all characters uppercase:
string upperCaseString = originalString.ToUpper();
Again, originalString remains unchanged.
5. Comparing References:
You can verify the immutability of strings by comparing references using the ReferenceEquals
method. If two strings are equal, but one is modified, they will not reference the same object:
string str1 = "immutable";
string str2 = str1; // Both reference the same string object
str2 += " example"; // Modifying str2
bool areEqualReferences = ReferenceEquals(str1, str2); // false
areEqualReferences
will be false because str1
and str2
reference different string objects after the modification.
In conclusion, the immutability of strings in C# ensures that once a string is created, it cannot be modified. Any operation that seems to modify a string results in the creation of a new string, leaving the original string unchanged. This property is important for data consistency and reliability in C# programs.