How to correctly compare strings in C #: Equals or == ?
string str1 = "s"; string str2 = "s"; Console.WriteLine("eq: " + str1.Equals(str2)); Console.WriteLine("==: " + (str1 == str2)); In both cases, the result is True , although the String is a class and the == operator should compare the links.
IlDasm showed that 2 variables are created and compared according to the Equals and == (op_Equality)
IL_0000: nop IL_0001: ldstr "s" IL_0006: stloc.0 IL_0007: ldstr "s" IL_000c: stloc.1 IL_000d: ldstr "eq: " IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: callvirt instance bool [mscorlib]System.String::Equals(string) IL_0019: box [mscorlib]System.Boolean IL_001e: call string [mscorlib]System.String::Concat(object, object) IL_0023: call void [mscorlib]System.Console::WriteLine(string) IL_0028: nop IL_0029: ldstr "==: " IL_002e: ldloc.0 IL_002f: ldloc.1 IL_0030: call bool [mscorlib]System.String::op_Equality(string, string) IL_0035: box [mscorlib]System.Boolean IL_003a: call string [mscorlib]System.String::Concat(object, object)
==operator compares only links (and thus j, sxyj is useless) only in Java. In C #, unlike Java, there is an operator overload. - VladD