Toshko Kosev
Toshko Kosev

Reputation: 27

C# comparing two object if they are equal

if(setting.ConvertedValue.Equals(m_MatchingModules[i].Group[j]))
{
}

I am working on a project and I need to check the code above if the values are equal. I never enter the if statement. My ConvertedValue variable is of type Object while Group is a list of Ints. I saw in the debugger that both values are equal 3 but the .Equals does not find them equal.

Upvotes: 1

Views: 132

Answers (3)

garryp
garryp

Reputation: 5776

Try using == instead. Equals is for checking object equality and can return false if the type is different even if the value is the same for value types.

someInt.Equals(someLong); // false

someInt == someLong; // true

Upvotes: 0

user4810968
user4810968

Reputation:

public override bool Equals(object obj)
{
    Test test = obj as Test;
    if (obj == null)
    {
        return false;
    }
    return Value == test.Value &&
        String1 == test.String1 &&
        String2 == test.String2;
}

Upvotes: 1

Abdul Rehman Sayed
Abdul Rehman Sayed

Reputation: 6672

Try using ValueType.Equals method.

if(ValueType.Equals(setting.ConvertedValue,m_MatchingModules[i].Group[j]))

Upvotes: 0

Related Questions