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?
Best Answer
When
==
is used on an expression of typeobject
, it'll resolve toSystem.Object.ReferenceEquals
.Equals
is just avirtual
method and behaves as such, so the overridden version will be used (which, forstring
type compares the contents).