Carl Nathan Mier
Carl Nathan Mier

Reputation: 51

C# Condition statement doesn't return true

I have a condition that compares two integers, but it never returns true even tho both numbers will be equal.

foreach (TreeViewItem item in Categories.Items)
            {
                if (subCategory.Tag == item.Tag)
                {
                    item.Items.Add(subCategory);
                }
            }

both are properties of TreeviewItem

TreeViewItem catItem = new TreeViewItem();
catItem.Tag = (int)row["CategoryID"];
Categories.Items.Add(catItem);

And

TreeViewItem subCategory = new TreeViewItem();
subCategory.Tag = (int)row["CategoryID"];

Even tho both values will become equal, the condition will return false and won't reach item.Items.Add(subCategory);

does anyone know what i'm missing? both are of the same type (int)... Thanks

Upvotes: 0

Views: 114

Answers (2)

LeffeBrune
LeffeBrune

Reputation: 3477

TrieViewItem.Tag is of object type. When you assign primitives to object reference they get converted to their corresponding classes, in your case Integer.

When you compare reference types using == operator you (unless the operator is overloaded) compare object references. The == operator will return true only if you compare a reference to itself. As your integer values are wrapped in two different objects, == will never return true.

You can read more about object equality on MSDN.

The correct way to compare in your case is:

if (object.Equals(subCategory.Tag, item.Tag))
{
   ...
}

Upvotes: 3

King King
King King

Reputation: 63337

Try using Equals instead:

if (object.Equals(subCategory.Tag, item.Tag)){
 //...
}

Comparing as you did will compare references, so they are of course won't be equal.

You can also cast each Tag to int and compare the casted results but using Equals is more convenient in this case.

Note that an object also has an Equals method, you can also use this but it's not safe if the object is null.

//subCategory.Tag should not be null
if (subCategory.Tag.Equals(item.Tag)){
   //...
}

Upvotes: 10

Related Questions