I have the Situation that I have an object
which I want to check for equality with another object
.
public static bool Equals(object a, object b)
{
return a.Equals(b);
}
A Problem occurs when a = 1 (integer)
and b = 1 (ushort (or basically not integer))
. I wondered whether this shouldn't yield true, but it does return false...
Edit
What makes it even worse is this:
Hashtable ht = new Hashtable();
ht.Add((int)1, "SOME STRING");
ht.Add((short)1, "SOME STRING");
ht.Add((long)1, "SOME STRING");
I think that the value '1' should only be allowed once.
Because they do not have the same type. You can try to cast them both to int, and then compare the ints, if the cast is successful.
Int32.Equals(object)
returns true only if the other object is also an instance ofInt32
:In code (
ILSpy
, .NET 4):Since
obj is int
returns false you get afalse
.Edit: ragarding to your edit(
Hashtable
with "similar" keys): if you don't want to allow duplicate objects use aDictionary<int, string>
instead(preferred) or add only ints to theHashTable
.Here's a simple class and implementation of equality comparers. As you can see, the standard apporach for equals is to make sure they are of the same time first, and then, that the inside matches (in our case, a string and a date).
If you want something else, you can always override it to your heart content, and cast both sides to something you're happy with :)