Languages
[Edit]
EN

C# / .NET - static Equals() vs non-static Equals()

7 points
Created by:
Wade
562

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);
    }
}

 

References

  1. Object.Equals Method - Microsoft Docs 

Alternative titles

  1. C# / .NET - static Equals() vs not static Equals()
  2. C# / .NET - object.Equals() vs myObject.Equals()
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join