불변(Immutable): 동일한 메모리 주소에 값 다시 쓰기가 불가능. 매번 새로운 메모리 주소에 값을 넣는다.
string a = "Hello"; // Heap에 문자열 객체 생성. a는 문자열 객체의 주소를 가리킴
string b = a; // b는 a가 가리키고 있는 주소 복사
string a = "Hello";
string b = a;
b = "World";
Console.WriteLine(a); // 결과 : "Hello"
Console.WriteLine(b); // 결과 : "World"
string a = "Hello";
a += " World";
new string(), ToString(), SubString() ...string.Intern()string a = "ABC";
string b = "ABC";
Console.WriteLine(object.ReferenceEquals(a, b)); // 결과 : True
string c = new string("ABC");
string d = string.Intern("ABC");
Console.WriteLine(object.ReferenceEquals(a, c)); // 결과 : False
Console.WriteLine(object.ReferenceEquals(a, d)); // 결과 : True
Console.WriteLine(object.ReferenceEquals(c, d)); // 결과 : False
string e = string.Intern(new string("ABC"));
Console.WriteLine(object.ReferenceEquals(a, e)); // 결과 : True
Console.WriteLine(object.ReferenceEquals(c, e)); // 결과 : False
문자열을 자주 연결하거나 변경하면 매번 새로운 문자열 객체를 생성하게 되어 GC의 부담이 커진다.
=> 이럴때 사용하는 것이 StringBuilder
string이 참조 타입이자 불변 객체인 이유는 ?