HiveBrain v1.2.0
Get Started
← Back to all entries
gotchacsharpCritical

C# difference between == and Equals()

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
andbetweenequalsdifference

Problem

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?

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.