c# – How C # strings are "referential"

Question:

Strings in C # are a reference type. But the following code

string s1 = "string 1";
string s2 = s1;
s2 = "string 2";
Console.Write(s1);

will output string 1 . What makes strings "referential" in C #?

Answer:

Everything is fine.

string s1 = "string 1";
string s2 = s1;
bool b = string.ReferenceEquals(s1, s2); // -> true
s2 = "string 2";
bool b2 = string.ReferenceEquals(s1, s2); // -> false

Those. before you wrote s2 = "string 2" , s1 and s2 referred to the same object, but as soon as you wrote this, a new object was created and s2 began to refer to it, and s1 remained referring to the first an object.

Scroll to Top