matrix
matrix

Reputation: 3090

What is the difference in string.Equals("string") and "String".Equals(string)?

Is there any difference in following two lines of code that compares the string values.

string str = "abc";

if(str.Equals("abc"))

and

if("abc".Equals(str))

in the first line I am calling the equals method on string variable to compare it with string literal. The second line is vice versa. Is it just the difference of coding style or there is a difference in the way these two statements are processed by the compiler.

Upvotes: 9

Views: 955

Answers (5)

Skuge
Skuge

Reputation: 1010

Yes, the way the compiler processed the statements is different. The function equals for String in most languages follows the same guidlines. Here is a semicode:

override def Equals(that:String):Boolean //Should override Object.Equals
  if(that==null) return false
  for i from 0 to this.length
    if(!this(i).Equals(that(i))) return false
  return true

Normally, the method will fisrt check that that IS a String, and that this and that have the same length.

You can see, as others pointed out, that if that is null the method returns false. On the other hand, the method is part of of String so it cannot be called on null. That is why in your exampleif str is null you will get a NullReferenceException.

That being said, if you know both variables are non-null Strings of the same length, both statements will evaluate to the same in the same time.

Upvotes: 1

Tim Robinson
Tim Robinson

Reputation: 54734

To add to the other answers: the static string.Equals("abc", str) method always avoids triggering a null reference exception, regardless of which order you pass the two strings.

Upvotes: 7

Paul Allen
Paul Allen

Reputation: 41

As mmyers said, you the second example will not throw a NullReferenceException and while allowing the program to "appear" to run error free, may lead to unintended results.

Upvotes: 4

Reed Copsey
Reed Copsey

Reputation: 564433

The only difference is that, in the first case, when you do:

str.Equals("abc")

If str is null, you'll get an exception at runtime. By doing:

"abc".Equals(str)

If str is null, you'll get false.

Upvotes: 30

Michael Myers
Michael Myers

Reputation: 191945

The difference is that in the second example, you will never get a NullReferenceException because a literal can't be null.

Upvotes: 10

Related Questions