Immutable String in C#

In this article we will discuss about the immutable string in C#.
  • 3265

Strings in .NET are immutable. Once a string is created, it cannot be modified. It may appear to you that you are reassigning a new value to the same string object but that's not true. Every time you assign a new value to an existing string object, a new object is being created and old object is being released by the CLR. That means you must be careful when dealing with string operations in C# and .NET. If you are doing lot of string operations, the StringBuilder class is recommended.

The following code snippet defines two string instances and then we change the value of the first string with the value of the second string. You would think, you are still using same old name variable but actually the name in the third line is a new object.

string name = "Mahesh Chand";
string
lastName = "Something else";
name = lastName;
Console
.WriteLine(name);

 

Further Readings

Ask Your Question 
 
Got a programming related question? You may want to post your question here
 

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.