As a newbie in C# want to know why Object
class of C# have two Equals
method with below signature.
public virtual bool Equals(object obj);
public static bool Equals(object objA, object objB);
While in Java there is only one equals
method.
As a newbie in C# want to know why Object
class of C# have two Equals
method with below signature.
public virtual bool Equals(object obj);
public static bool Equals(object objA, object objB);
While in Java there is only one equals
method.
First
public virtual bool Equals(object obj);
is a standard, typical etc. method to compare objects: if this
equals to obj
similar to Java's
Second
public static bool Equals(object objA, object objB);
is a kind of sugar for you not to compare objA
with null
each time you want to compare objA
, objB
instances
https://referencesource.microsoft.com/#mscorlib/system/object.cs,f2a579c50b414717
public static bool Equals(Object objA, Object objB)
{
if (objA==objB) {
return true;
}
if (objA==null || objB==null) {
return false;
}
return objA.Equals(objB);
}
Java does have a similar method:
// Please, note Objects instead of Object
Objects.equals(Object a, Object b);
The first one compares the current instance with the one provided in the parameter. The later compares A with B as its a static method
The first "Equals" method compares the caller object with the arguments.... CallerObject.Equals(targetComparerObject), Moreover, we can also define a custom override for this method in child classes.
The second equals method compares two arguments with each other... :) we cannot override it.
Moreover, in Java the equals methods only compares the memory location. that means when we say obj1.equals(obj2), by default it compares only references, whether they are pointing to same location or not... If we want any custom comparison, we need to override it in JAVA..
public virtual bool Equals(object obj)
This is a object method available in every class object. You use this method to compare current object with the one you passed as a argument.
public static bool Equals(object objA, object objB)
This is a class method available in the Object
class which is a top most parent class of all the other classes in C# which means every class in C# is derived from base class Object
. It is available as static requiring you to pass two objects as the arguments to get compared.
For more information and examples, you can refer to the documentation.
Object.Equals(obj1, obj2)
https://msdn.microsoft.com/en-us/library/w4hkze5k(v=vs.110).aspx
obj1.Equals(obj2)
https://msdn.microsoft.com/en-us/library/bsc2ak47(v=vs.110).aspx
I don't see any difference between C# and Java in this case. Both do object comparison. It's just about language implementation. C# implemented it in two ways and Java defined it in its own way having it as a object method rather than going for a static one like C#.