[Solved] Difference between == and Equals in C# [duplicate]


== is an operator, which, when not overloaded means “reference equality” for classes (and field-wise equality for structs), but which can be overloaded. A consequence of it being an overload rather than an override is that it is not polymorphic.

Equals is a virtual method; this makes it polymorphic, but means you need to be careful not to call it on null instances.

As a rule of thumb:

  • if you know the type of something, and know it has an == overload (most core types such as string, int, float, etc have == meanings), then use ==
  • if you don’t know the type, Equals(a,b) may be recommended, as this avoids the null issue
  • if you really want to check for the same instance (reference equality), consider using ReferenceEquals(a,b), as this will work even if the == is overloaded and Equals overridden
  • when using generics, consider EqualityComparer<T>.Default.Equals(a,b) which avoids the null issue, supports Nullable-of-T, and supports IEquatable-of-T

2

solved Difference between == and Equals in C# [duplicate]