C# FAQ: Are CSharp strings immutable

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:FAQs
edit

Are C# strings immutable?

Both the Java and C# string classes—C#: System.String, Java: java.lang.String—are immutable. Immutable means that—once created—string values cannot be changed. Methods which may seem to modify string contents, in fact, create a new string containing the new value. The original string remains unchanged.

The following examples do not modify the strings in question but return new strings containing the desired modifications:

String aString = "C# Online.NET";     // C# example
aString.ToLower();

The C# String class can be written either as String or string.

String aString = "C# Online.NET";     // Java example 
aString.toLowerCase();

To create a string type object which does allow modification, use a mutable type string class—C#: System.Text.StringBuilder, Java: java.lang.StringBuffer.

See also


Personal tools