I have a condition in a silverlight application that compares 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?
When we create any object there are two parts to the object one is the content and the other is reference to that content.
==
compares both content and reference;equals()
compares only contenthttp://www.codeproject.com/Articles/584128/What-is-the-difference-between-equalsequals-and-Eq
The only difference between Equal and == is on object type comparison. in other cases, such as reference types and value types, they are almost the same(either both are bit-wise equality or both are reference equality).
object: Equals: bit-wise equality ==: reference equality
string: (equals and == are the same for string, but if one of string changed to object, then comparison result will be different) Equals: bit-wise equality == : bit-wise equality
See here for more explanation.
Adding one more point to the answer.
.EqualsTo()
method gives you provision to compare against culture and case sensitive.== 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 and If their types are same it performs == operator else it returns false.
Really great answers and examples!
I would just like to add the fundamental difference between the two,
With that concept in mind, if you work out any example (by looking at left hand and right hand reference type, and checking/knowing if the type actually has == operator overloaded and Equals being overriden) you are certain to get the right answer.
As far as I understand it the answer is simple:
I hope i'm correct and that it answered your question.