5 ways for equality check in .net .. why? and which to use?

前端 未结 4 1200
北恋
北恋 2020-12-13 00:14

While learning .net (by c#) i found 5 ways for checking equality between objects.

  1. The ReferenceEquals() method.
  2. The virtual Equals() method. (System.O
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-13 00:46

    For primitives, stick with the == operator.

    In most objects supplied in the .NET framework and any custom objects you create the .Equals() method and the == operator will only check to see if two objects refer to the same object on the heap.

    The purpose of the IEquatable interface is to override the .Equals() method to change its behavior from checking for referential equality to check for value equality. The System.String type is an example of a built-in .NET object which implements this interface.

    The .ReferenceEquals() method provides a way for developers who've overriden the standard .Equals() method to still be able to check two objects for referential equality.

提交回复
热议问题