Operator Overloading

  • Thread starter Thread starter Stephen Smith
  • Start date Start date
S

Stephen Smith

Help appreciated.

I have a class User which implements an interface IUser. The interface has a
property Name that obviously the class implements.

The class is passed around the object model by its respective interface,
however, this is causing a problem when two IUser interfaces are compared.
If both users are called Bob then I want the comparison to return a match.

I have overridden all the obvious on the class User, Equals(),
GetHashCode(), the == and != operators for both the User class and a IUser
object.

In the comparison if I cast one of the interface objects to a User then the
overloaded operators kick in and everything is hunky-dory. If however, I
leave them both as IUser then the operators are not called and comparison
fails.

How do I get over this problem?

Thanks Steve
 
Stephen Smith said:
Help appreciated.

I have a class User which implements an interface IUser. The interface has a
property Name that obviously the class implements.

The class is passed around the object model by its respective interface,
however, this is causing a problem when two IUser interfaces are compared.
If both users are called Bob then I want the comparison to return a match.

I have overridden all the obvious on the class User, Equals(),
GetHashCode(), the == and != operators for both the User class and a IUser
object.

In the comparison if I cast one of the interface objects to a User then the
overloaded operators kick in and everything is hunky-dory. If however, I
leave them both as IUser then the operators are not called and comparison
fails.

How do I get over this problem?

Call .Equals instead of using ==. Operator overloading doesn't work
polymorphically, which is one of the reasons I avoid it.
 
Back
Top