Tuesday, February 23, 2021

Immutability of String Objects In C#

String objects are immutable, they  cannot be changes after they have been created. All of the String methods and C# operators that appear to modify a string actually return the results in a new object.

For example: 

When the contents of s1 and s2 are concatenated to form a single string, the two original string are unmodified. The += operator creates a new string that contains the combined contents. That  new  object is assigned to the variable s2, and the original object that was assigned to s1 is released for garbage collection because no other variable holds a reference to it.

string s1 = "Hello ";
string s2 = "World";
// Concatenate s1 and s2. This actually creates a new
// string object and stores it in s1, releasing the
// reference to the original object.

s1 += s2;
System.Console.WriteLine(s1);

// Output: A string is more than the sum of its chars.



No comments:

Post a Comment

Featured Post

What is JavaScript? What is the role of JavaScript engine?

  The JavaScript is a Programming language that is used for converting static web pages to interactive and dynamic web pages. A JavaScript e...