Lets say we have two objects o1 & o2 defined as System.Object, in my situtaion o1 & o2 can be any of the following types:
So how can I check that o1 & o2 are equal, therefore are the same object or both have the same type & value.
Can I just do o1 == o2
or do I need to do o1.Equals(o2)
or something else?
Thanks,
AJ
“Using the equality (==) and inequality (!=) operators to compare two objects does not check to see if they have the same values. Rather it checks to see if both object references point to exactly the same object in memory. The vast majority of the time, this is not what you want to do.”
The Equality Operator ( ==) is the comparison operator and the Equals() method in C# is used to compare the content of a string. The Equals() method compares only content.
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).
I would suggest you use
object.Equals(o1, o2)
as that will cope with nullity as well. (That assumes you want two null references to compare as equal.)
You should not use ==
because operators are not applied polymorphically; the types overload == but they don't override it (there's nothing to override). If you use
o1 == o2
that will compare them for reference identity, because the variables are declared to be of type object
.
Using o1.Equals(o2)
will work except in the case where o1
is null - at which point it would throw a NullReferenceException
.
Operator == compare objects by reference, and method Equals compare objects by value.
For Example:
StringBuilder s1 = new StringBuilder(“Yes”);
StringBuilder s2 = new StringBuilder(“Yes”);
Console.WriteLine(s1 == s2);
Console.WriteLine(s1.Equals(s2));
Will display:
False
True
Value objects can be compared either by == or Equals.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With