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
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.
'Equals' should work for strings and the value types you listed.
'==' Will fail for things like the following code because the references to the boxed objects aren't the same:
int x = 1;
int y = 1;
Object o1 = x;
Object o2 = y;
Edit:
I noticed the stringbuilder example given above, but since you are using strings and their equality operator is overridden they'd actually work with either "==" or ".Equals", the following code
string s1 = "Yes";
string s2 = "Yes";
Console.WriteLine(s1 == s2);
Console.WriteLine(s1.Equals(s2));
Outputs
True
True
I would use Object.Equals(o1,o2)
- ref. MSDN
Jon has supplied excellent explanations of why this would be the best usage.
object.Equals(obj1, obj2) // This is the way prefered and the best practice for equality comparison.
Thus you might also consider overriding the Equals method when working with custom objects (not the case here appearently).
public class Something {
public long Id { get; set; }
public string Name { get; set; }
public override bool Equals(object obj) {
if (obj == null)
return false;
if (((Something)obj) == null)
return false;
Something s = (Something)obj;
return this.Id == s.Id && string.Equals(this.Name, s.Name);
}
public bool Equals(Something s) {
if (s == null)
return false;
return this.Id == s.Id && string.Equals(this.Name, s.Name);
}
}
This way, you will assure that your custom objects are equal.