Drahcir Drahcir - 1 year ago 94
C# Question

C# difference between == and Equals()

I have a condition in a silverlight application that compares 2 strings, for some reason when I use

it returns false while
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?

Answer Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download