C# difference between == and Equals()

前端 未结 17 1371
走了就别回头了
走了就别回头了 2020-11-21 06:56

I have a condition in a silverlight application that compares 2 strings, for some reason when I use == it returns false while .Equals()

17条回答
  •  礼貌的吻别
    2020-11-21 07:58

    == and .Equals are both dependent upon the behavior defined in the actual type and the actual type at the call site. Both are just methods / operators which can be overridden on any type and given any behavior the author so desires. In my experience, I find it's common for people to implement .Equals on an object but neglect to implement operator ==. This means that .Equals will actually measure the equality of the values while == will measure whether or not they are the same reference.

    When I'm working with a new type whose definition is in flux or writing generic algorithms, I find the best practice is the following

    • If I want to compare references in C#, I use Object.ReferenceEquals directly (not needed in the generic case)
    • If I want to compare values I use EqualityComparer.Default

    In some cases when I feel the usage of == is ambiguous I will explicitly use Object.Reference equals in the code to remove the ambiguity.

    Eric Lippert recently did a blog post on the subject of why there are 2 methods of equality in the CLR. It's worth the read

    • http://blogs.msdn.com/ericlippert/archive/2009/04/09/double-your-dispatch-double-your-fun.aspx

提交回复
热议问题