Zarathos Zarathos - 1 month ago 8
C# Question

Compare Two Enum Values Cast to Object

I created a custom

UserControl
. Inside it there is a
ComboBox
which is filled with the values of an enumerator during initialization:

m_ComboBox.Items.AddRange((Object[])Enum.GetValues(typeof(Categories)));


Since I want to keep track of the previous
ComboBox.SelectedItem
, I created a variable in which I store its last value:

private Object m_LastCategory;

private void ComboBoxSelectedIndexChanged(Object sender, EventArgs e)
{
if (m_ComboBox.SelectedItem != m_LastCategory)
DoSomething();

m_LastCategory = m_ComboBox.SelectedItem;
}


The if statement is not working as expected. Actually, even if
m_LastCategory
and the current
SelectedItem
are different (and I know it for sure), it always returns
true
.

I know, I could simply cast both variables back to enum and then compare them getting the right result. But I was using
Object
in order to avoid a constant boxing/unboxing of the values and keep my code more elegant. So I would like to know if there is a way to deal with this issue.

The only working alternative I found so far is this one:

if (m_ComboBox.SelectedItem.ToString() != m_LastCategory.ToString())


And I'm still not sure it's a correct way to proceed.

Answer

I know, I could simply cast both variables back to enum and then compare them getting the right result.

Do that. Object equality by default is reference equality, i.e. are those two references pointing to the same location in memory. Two boxed enums are two objects at two different locations in memory, which is why they are always unequal regardless of the value they contain.

In addition, it's in general a good idea to retain as much type information as you can; this lets the compiler help you write correct programs. Typing your m_LastCategory variable as Object works against this principle.