evanmcdonnal
evanmcdonnal

Reputation: 48114

Force implementing classes to use their own type as the type for a method parameter

I have an interface that a set of objects implement. I would like all objects in the set to implement a MemberWiseCompare(ImplementingType rhs) method which requires they use their own type as the argument type.

After a little research it seems that I could change my interface from something like;

  public interface IMyInterface

to

 public interface IMyInterface<T>

Then use T as the argument type for the MemeberWiseCompare method. However, I'm hoping there is an alternative solution because this produces something like 200 compiler errors and thus will require a lot of work to do. Also I think it could cause some problems because there are places where I use IMyInterface as a return or argument type and I'm sure changing all of those to the generic version would complicate the code. Is there an alternative way of doing this? Are there any better options?

Upvotes: 4

Views: 1358

Answers (1)

Lee
Lee

Reputation: 144206

I assume your interface currently looks like:

public interface IMyInterface
{
    bool MemberwiseCompare(object other);
}

in which case you could change it to:

public interface IMyInterface
{
    bool MemberwiseCompare<T>(T other) where T : IMyInterface;
}

This keeps the interface non-generic, but gives you some extra type safety when passing invoking MemberwiseCompare. The implementations shouldn't need to change (apart from their signatures) since they currently will have to do a runtime type check anyway. I assume most of the call sites won't need to change either due to type inference on generic parameters.

EDIT: Another possibility is that you could add the generic IMyInterface<T> interface, and have your implementing classes implement both interfaces (one will need to be implemented explicitly). Then you could gradually move over to the generic interface while obsoleting the non-generic version e.g.

public class MyClass : IMyInterface, IMyInterface<MyClass>
{
    public bool MemberwiseCompare(MyClass other) { ... }
    bool IMyInterface.MemberwiseCompare(object other)
    {
        MyClass mc = other as MyClass;
        return mc != null && this.MemberwiseCompare(mc);
    }
}

Upvotes: 5

Related Questions