Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net object equality

Tags:

c#

.net

Lets say we have two objects o1 & o2 defined as System.Object, in my situtaion o1 & o2 can be any of the following types:

  • String
  • Int32
  • Double
  • Boolean
  • DateTime
  • DBNull

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

like image 409
AJ. Avatar asked Mar 04 '10 14:03

AJ.


People also ask

Why can you not use == for objects?

“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.”

What is == and Equals in C#?

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.

Can we use Equals for object?

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).


2 Answers

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.

like image 78
Jon Skeet Avatar answered Oct 15 '22 04:10

Jon Skeet


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.

like image 4
šljaker Avatar answered Oct 15 '22 03:10

šljaker