M
MaSTeR
Can anyone provide a practical short example of why in C# I shouldn't
compare two strings with == ?
If I write this in JAVA
String string1 = "Widget";
if (string1 == "Widget")
System.Console.WriteLine("String1 Equal.");
String string2 = new String("Widget");
if (string2 == "Widget")
System.Console.WriteLine("String2 Equal.");
The comparison og string2 will fail because the first time string1 and
"Widget" will be the same object because the VM use interning to avoid
repeated strings in memory.
String string2 = new String("Widget"); will tell the VM that I want a brand
new object don't intern this string (that is don't make it a new reference
to the old object string1 points to) hence the comparison will fail.
if in C# you write the same code changing
String string2 = new String("Widget");
to
String string2 = new String(new char[]{'W','i','d','g','e','t'});
The second comparison will succeed anyway, it seems there no obvious way to
make the same string be stored in different object because .Net forces
interning.
Thanks for your help.
compare two strings with == ?
If I write this in JAVA
String string1 = "Widget";
if (string1 == "Widget")
System.Console.WriteLine("String1 Equal.");
String string2 = new String("Widget");
if (string2 == "Widget")
System.Console.WriteLine("String2 Equal.");
The comparison og string2 will fail because the first time string1 and
"Widget" will be the same object because the VM use interning to avoid
repeated strings in memory.
String string2 = new String("Widget"); will tell the VM that I want a brand
new object don't intern this string (that is don't make it a new reference
to the old object string1 points to) hence the comparison will fail.
if in C# you write the same code changing
String string2 = new String("Widget");
to
String string2 = new String(new char[]{'W','i','d','g','e','t'});
The second comparison will succeed anyway, it seems there no obvious way to
make the same string be stored in different object because .Net forces
interning.
Thanks for your help.