Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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.

like image 804
matrix Avatar asked Jun 29 '10 16:06

matrix


People also ask

What's the difference between using == and .equals on a string?

In simple words, == checks if both objects point to the same memory location whereas . equals() evaluates to the comparison of values in the objects. If a class does not override the equals method, then by default, it uses the equals(Object o) method of the closest parent class that has overridden this method.

What is difference between == and .equals in Java?

The major difference between the == operator and . equals() method is that one is an operator, and the other is the method. Both these == operators and equals() are used to compare objects to mark equality.

What is the difference between == and .equals method in C#?

The Equality Operator ( ==) is the comparison operator and the Equals() method in C# is used to compare the content of a string. The Equals() method compares only content.

What does .equals mean in Java?

Definition and Usage The equals() method compares two strings, and returns true if the strings are equal, and false if not.


2 Answers

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.

like image 190
Reed Copsey Avatar answered Oct 23 '22 15:10

Reed Copsey


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

like image 21
Michael Myers Avatar answered Oct 23 '22 16:10

Michael Myers