C# difference between == and Equals()

2018-12-31 01:52发布

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?

标签: c# .net equals
16条回答
看风景的人
2楼-- · 2018-12-31 02:23

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 content

http://www.codeproject.com/Articles/584128/What-is-the-difference-between-equalsequals-and-Eq

查看更多
长期被迫恋爱
3楼-- · 2018-12-31 02:23

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.

查看更多
几人难应
4楼-- · 2018-12-31 02:24

Adding one more point to the answer.

.EqualsTo() method gives you provision to compare against culture and case sensitive.

查看更多
低头抚发
5楼-- · 2018-12-31 02:32

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

查看更多
无色无味的生活
6楼-- · 2018-12-31 02:32

Really great answers and examples!

I would just like to add the fundamental difference between the two,

Operators such as == are not polymorphic, while Equals is

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.

查看更多
残风、尘缘若梦
7楼-- · 2018-12-31 02:33

As far as I understand it the answer is simple:

  1. == compares object references.
  2. .Equals compares object content.
  3. String datatypes always act like content comparison.

I hope i'm correct and that it answered your question.

查看更多
登录 后发表回答