Reputation: 652
I have an enum type defined: EnumType Now imagine
object A = EnumType.Value1;
object B = EnumType.Value2;
I would like to make the comparison ( A == B ) give me the correct result independent of the type of Enum used. In the comparison, the object will always contain enums, and both will be of the same type.
How can I achieve this?
Upvotes: 7
Views: 7182
Reputation: 347226
There is a good article on MSDN on when to use == and when to use Equals.
Basically there are 2 types of equality: Reference equality and value equality. If 2 objects have reference equality they hence therefore also have value equality (both references point to the same object so of course their values are the same).
The opposite, (and in your case) is not always true though. If 2 objects have value equality they don't necessarily have reference equality. In your case ==
is acting as reference equality.
Usually what you want is Equals
, it is a virtual method defined in System.Object.
What you usually don't want for reference types is ==
, it usually compares whether two references refer to the same object.
In your case A
and B
are boxed into 2 different objects. A
refers to the first and B
refers to the second. ==
is testing and seeing that both are referring
to different things.
Upvotes: 6
Reputation: 57210
Just use A.Equals(B)
, it will call the inner type Equals.
In your case you cannot use ==
because A and B are boxed in 2 different objects.
Upvotes: 3