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?
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
AandBare boxed into 2 different objects.Arefers to the first andBrefers to the second.==is testing and seeing that both arereferringto different things.