1

I have a checklist that asks me to use string.Equals() while checking the equality of two strings. And as far as I know, both Equals() and == yield same result when operated upon strings. For example shown below,

        string str1 = "Same String";
        string str2 = "Same String";

        Console.WriteLine(str1==str2);               //True
        Console.WriteLine(string.Equals(str1,str2)); //True

So, I wanted to know which is better here? Does it make any difference in the performance?

Many thanks in advance!

pradeepradyumna
  • 952
  • 13
  • 34

2 Answers2

2

I would suggest string.Equals as equality(==) operator internally use string.Equals first check for references equality and then for value equality, hence it would be better to use string.Equals than == in case of string variables.

Vishnu Babu
  • 1,183
  • 1
  • 13
  • 37
  • Also, even in 2022, at least in the latest .Net Framework 64-bit, the == operator version, the 'System.String.op_Equality(System.String, System.String), will often not get inlined, even though it's only calling static String.Equals(String,String). – Beeeaaar Sep 05 '22 at 19:03
1

.equals() is considered a good practice because chain comparaison isnt as easy for a computer than integer comparaison.

When comparing an object reference to a string (even if the object reference refers to a string), the special behavior of the == operator specific to the string class is ignored.

Normally (when not dealing with strings, that is), Equals compares values, while == compares object references. If two objects you are comparing are referring to the same exact instance of an object, then both will return true, but if one has the same content and came from a different source (is a separate instance with the same data), only Equals will return true. However, as noted in the comments, string is a special case because it overrides the == operator so that when dealing purely with string references (and not object references), only the values are compared even if they are separate instances

Jorel Amthor
  • 1,264
  • 13
  • 38
  • It wasn't clear to me about 'chain comparison'. Can you please throw some more light on it, as in what exactly was being referred to and why exactly using strings.Equals() a good practice. – pradeepradyumna Feb 01 '16 at 11:50