Operator Overloading

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
 
J

Jon Skeet [C# MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top