I have a private class, User that implements an interface, IQMUser, with
public static bool operator ==( User a, User b ) { return Equals( a, b ); }
public static bool operator !=( User a, User b ) { return !Equals( a, b ); }
public override bool Equals ( object obj )
{
User other = obj as User;
return m_LMUser.UserID == other.m_LMUser.UserID;
}
public override int GetHashCode ( )
{
return m_LMUser.GetHashCode ( );
}
User is a member of a public class, UserManager, which has GetUsers( ), which returns IList<IQMUser>. In another class, I have
IQMUser otherUser = UserManager.GetUsers( )
.Where( u => u != CurrentUser )
.FirstOrDefault( );
Now, I know for a fact that GetUsers returns an object that has the same m_LMUser.UserID as CurrentUser. However, the test u != CurrentUser is always true, even in that case.
I have set breakpoints at each of the operator overloads and the Equals override in User, but none of them hit.
I then changed the query to
IQMUser otherUser = UserManager.GetUsers( )
.Where( u => !u.Equals( CurrentUser ) )
.FirstOrDefault( );
This hits the overridden Equals method as expected.
What is wrong with my operator overloads that Linq doesn’t even hit them?
If I understand your inheritance hierarchy correctly, the type in the “Where” seems to be
IQMUser(the base class), while theoperator ==is implemented on the subclassUser.Since
operator ==is not virtual, the Linq Where expression with typeIQMUserwill run theIQMUser operator ==instead of the one implemented onUser.Equals on the other hand is virtual and the override works as it should, allowing it to work correctly if you call it directly instead.