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#.
xxxxxxxxxx
1
Object firstObject = ...
2
Object secondObject = ...
3
4
bool result = object.Equals(firstObject, secondObject); // or: Object.Equals(firstObject, secondObject)
Syntax:
xxxxxxxxxx
1
public static bool Equals(object? objA, object? objB);
xxxxxxxxxx
1
Object firstObject = ...
2
Object secondObject = ...
3
4
bool result = firstObject.Equals(secondObject);
Syntax:
xxxxxxxxxx
1
public virtual bool Equals(object? obj);
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:
xxxxxxxxxx
1
public class Object
2
{
3
public static bool Equals(object? objA, object? objB)
4
{
5
if (objA == null)
6
return objB == null;
7
8
if (objB == null) return false;
9
if (objA == objB) return true;
10
11
return objA.Equals(objB);
12
}
13
}