Monday, August 15, 2016

Immutable C#

String is immutable 
  • Once created, it cannot be changed. 
  • Each method of string is returns a new string instead of altering the original.
  • You can re-reference the back to original to get back the new string.
  • Thread safe
  • Low Perfomance when continuous change of value.
StringBuilder is mutable 
  • Efficient way to repeatedly append of string.

int i = 1;
int newI = i;
newI = 2;

Console.WriteLine("Old int :" + i);
Console.WriteLine("New int :" + newI);

Console.WriteLine("====================");

string str = "mystring";
string newString = str;
string newString2 = str.Replace('s', 'o');
newString = "asd";

Console.WriteLine("Old String :" + str);
Console.WriteLine("New String :" + newString);
Console.WriteLine("New String 2:" + newString2);

Console.WriteLine("==================");

MyClass myClass = new MyClass { myString = "TestString", myInt = 1 };
MyClass newMyClass = myClass;
newMyClass.myString = "Test";
newMyClass.myInt = 2;

Console.WriteLine("Old Object String :" + myClass.myString + "|Old Class Int :"+ myClass.myInt);
Console.WriteLine("New Object String :" + newMyClass.myString + "|Old Class Int :" + newMyClass.myInt);

--------------Result ----------------------
Old int : 1 //Value Type, so no change
New int : 2
====================
Old String : mystring   //immutable string , so no change
New String : asd
New String 2: myotring
==================
Old Object String : Test|Old Class Int :2 //object & object inside value type is reference type, so will change
New Object String : Test|Old Class Int :2  

No comments:

Post a Comment