Skip to main content

Posts

Showing posts with the label #Immutable

#C# String is Immutable in C#

There is a term called immutable, which means the state of an object can't be changed after is has been created.  A string is an immutable type. The statement that a string is immutable means that, once created, it is not altered by changing the value assigned to it. If we try to change the value of a string by concatenation (using + operator) or assign a new value to it, it actually results in creation of a new string object to hold a reference to the newly generated string. It might seem that we have successfully altered the existing string. But behind the scenes, a new string reference is created, which points to the newly created string. string s1="Hi"; string s2=s1; s2=s2+"Raj"; s1  -> pointer to data "Hi" s2  -> pointer to date "Hi" -> pointer to data "Hi Raj" here s2 is pointing to new data. that is s2 pointer is changed.(Immutable)