EN
C# / .NET - static Equals() vs non-static Equals()
7
points
In this short article, we would like to explain what is difference between static Equals() vs non-static Equals() in C#.
Usage examples
1. Static Equals() can be accessed using:
Object firstObject = ...
Object secondObject = ...
bool result = object.Equals(firstObject, secondObject); // or: Object.Equals(firstObject, secondObject)
Syntax:
public static bool Equals(object? objA, object? objB);
2. Non-static Equals() can be accessed using:
Object firstObject = ...
Object secondObject = ...
bool result = firstObject.Equals(secondObject);
Syntax:
public virtual bool Equals(object? obj);
Difference explaination
Static Equals() should be used when some of the compared objects may be null - it was created to prevent against NullReferenceException occurrences. Non-static Equals() method is called when some argument is not null.
If we would like to propose how public static bool Equals(object? objA, object? objB) method may be implemented, we could use:
public class Object
{
public static bool Equals(object? objA, object? objB)
{
if (objA == null)
return objB == null;
if (objB == null) return false;
if (objA == objB) return true;
return objA.Equals(objB);
}
}