gotchacsharpCritical
C# difference between == and Equals()
Viewed 0 times
andbetweenequalsdifference
Problem
I have a condition in a silverlight application that compares 2 strings, for some reason when I use
Here is the code:
Any reason as to why this is happening?
== 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?
Solution
When
== is used on an expression of type object, 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).Context
Stack Overflow Q#814878, score: 544
Revisions (0)
No revisions yet.