Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does string equality compares characters?

Tags:

c#

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?

like image 643
MBen Avatar asked Jun 22 '26 18:06

MBen


2 Answers

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.

like image 193
Oded Avatar answered Jun 24 '26 09:06

Oded


[...] 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

like image 36
Stephan Bauer Avatar answered Jun 24 '26 07:06

Stephan Bauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!