Tuesday, January 29, 2013

C# difference between `==` and .Equals()

C# difference between `==` and .Equals()

I have a condition in a silverlight application that comapres 2 strings, for some reason when I use '==' it returns false while .Equals() returns true. Here is the code :

 if (((ListBoxItem)lstBaseMenu.SelectedItem).Content.Equals("Energy Attack"))  { // Execute code  }   if (((ListBoxItem)lstBaseMenu.SelectedItem).Content == "Energy Attack")  { // Execute code  } 

Any reason as to why this is happening?

Answers & Comments...

Answer: 1

When == is used on an object type, it'll resolve to System.Object.ReferenceEquals.

Equals is just a virtual method and behaves as such, so the overridden version will be used (which, for string type compares the contents).

by : Mehrdad Afsharihttp://stackoverflow.com/users/33708

Answer: 2

INACCURATE: String.Equals compares string content, but "==" compares object references. If the two strings you are comparing are referring to the same exact instance of a string, both will return true, but if one of the strings has the same content and came from a different source (is a separate instance of a string), only Equals will return true.

CORRECTION: The second comment associated with this post is correct. The following code illustrates the issue:

string s1 = "test"; string s2 = "test"; string s3 = "test1".Substring(0, 4); object s4 = s3; Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s2), s1 == s2, s1.Equals(s2)); Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s3), s1 == s3, s1.Equals(s3)); Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s4), s1 == s4, s1.Equals(s4)); 

The output is:
True True True
False True True
False False True

by : BlueMonkMNhttp://stackoverflow.com/users/78162

Answer: 3

What == and .Equals does is both dependent upon the behavior defined in the actual type and the actual type at the call site. Both are just methods / operators which can be overridden on any type and given any behavior the author so desires. In my experience, I find it's common for people to implement .Equals on an object but neglect to implement operator ==. This means that .Equals will actually measure the equality of the values while == will measure whether or not they are the same reference.

When I'm working with a new type whose definition is in flux or writing generic algorithms, I find the best practice is the following

  • If I want to compare references in C#, I use Object.ReferenceEquals directly (not needed in the generic case)
  • If I want to compare values I use EqualityComparer<T>.Default

In some cases when I feel the usage of == is ambiguous I will explicitly use Object.Reference equals in the code to remove the ambiguity.

Eric Lippert recently did a blog post on the subject of why there are 2 methods of equality in the CLR. It's worth the read

by : JaredParhttp://stackoverflow.com/users/23283

Answer: 4

I am a bit confused here. If the runtime type of Content is of type string, then both == and Equals should return true. However, since this does not appear to be the case, then runtime type of Content is not string and calling Equals on it is doing a referential equality and this explains why Equals("Energy Attack") fails. However, in the second case, the decision as to which overloaded == static operator should be called is made at compile time and this decision appears to be ==(string,string). this suggests to me that Content provides an implicit conversion to string.

by : Mehmet Arashttp://stackoverflow.com/users/95437

Answer: 5

I would add that if you cast your object to a string then it will work correctly. This is why the compiler will give you a warning saying "Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'"

by : MikeKullshttp://stackoverflow.com/users/701485

Answer: 6

Adding one more point to the answer.

.EqualsTo method gives you provision to compare against culture and case sensitive.

by : Balahttp://stackoverflow.com/users/764963

Answer: 7

== Operator 1. If operands are Value Types and their values are equal, it returns true else false. 2. If operands are Reference Types with exception of string and both refer to same object, it returns true else false. 3. If operands are string type and their values are equal, it returns true else false.

.Equals 1. If operands are Reference Types, it performs Reference Equality that is if both refer to same object it returns true else false. 2. If Operands are Value Types then unlike == operator it checks for their type first. If their types are same it performs == value type equality else it returns false.

by : kashifhttp://stackoverflow.com/users/1290058




No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog