I am just a bit confused with strings, and their comparison.
What I understand is that doing this :
string one = "stackoverflow";
string two = "stackoverflow";
bool equal = one == two;
This will compare character by character right?
Why is this the case? if string are immutable, and two variables will always refer to the same string if they have equal characters. Why doesn’t the compiler just checks the references?
If there is one place where I would think that references equality means value equality I would think that would be for strings. What am I missing?
It is true that string literals are automatically interned, but not all strings are interned. When you build a string dynamically or get it somehow during runtime, it will not be interned by default – you need to call
String.Internfor that to happen.This means you can have identical string instances with different references.
So, in your case, if you dynamically build the string “stackoverflow” twice and assign each to the variables
oneandtwo, the references ofoneandtwowill be different, though the value is identical.