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.Intern for 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 one and two, the references of one and two will be different, though the value is identical.
[...] Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive. [...]
See MSDN documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With