I need to compare 2 objects of the same class. I was sure that the fastest way will be to read them as number, so (int)Obj1 - (int)Obj2
will give me 0 if they are equal. However, it looks like I cant cast it that way. Do you know how to fast compare objects? I wish to avoid going through all parameters, because there is no need to know where is the difference.
Asked
Active
Viewed 415 times
0

Alexei Levenkov
- 98,904
- 14
- 127
- 179

Michał Woliński
- 346
- 2
- 12
-
2No quick way unless you have already implemented `IEquatable` or overridden `Equals`. – Arghya C Dec 11 '15 at 19:16
-
2See [this](http://stackoverflow.com/questions/375996/compare-the-content-of-two-objects-for-equality) for binary equivalence. – Yuval Itzchakov Dec 11 '15 at 19:18
-
The more robust solution is to **serialize and compare**. But it will not be fast. – thepirat000 Dec 11 '15 at 21:13
-
@thepirat000 I can't serialize those objects. Checked Yuval Itzchakov solution and post marked as "working" does not work. Returns true with objects with different values at same property. However code looks correctly for me. – Michał Woliński Dec 12 '15 at 14:18
1 Answers
1
If you want to compare if 2 references is from the same object, you can use equals method. If you want to compare the properties from the class with each other, then you need to override the Equals method in your class.
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (!(obj is Person))
return false;
return Name == ((Person) obj).Personer;

Kasper Due
- 699
- 7
- 19
-
1I've always preferred `Person p = obj as Person; if(obj == null) return false;` to avoid potentially casting twice. Also I'd think you'd want to compare the same properties in both instances `return Name == ((Person obj).Name;` or with my suggestion `return Name == p.Name;` – juharr Dec 11 '15 at 19:22
-
1Not completely wrong, but... Since there is no way to know if `Equals` uses reference or value semantic statement that "to compare if 2 references is from the same object, you can use equals..." is at very best incomplete. I.e. what about strings? – Alexei Levenkov Dec 11 '15 at 19:29
-
-
1Side note: there are cases when your code will incorrectly compare to `null` - see http://stackoverflow.com/questions/3143498/why-check-this-null – Alexei Levenkov Dec 11 '15 at 19:35