Can Poyrazoğlu
Can Poyrazoğlu

Reputation: 34780

How to reference the implementing class from an interface?

I'm creating an interface where I need a method to reference a class instance of the class that implements the interface. Here is an example:

class MyClass : IMyInterface{
    public void MyMethod(MyClass a){...} //implemented from the interface.
}

So how should I implement my interface (without generics) to reference the class that it is implemented in?

interface IMyInterface{
    void MyMethod(??? a);
}

What should come to the ??? part?

Thanks, Can.

Upvotes: 2

Views: 4924

Answers (2)

Ani
Ani

Reputation: 113402

The C# type system isn't sophisticated enough to represent the notion of a "self" type well. IMO, the ideal solution is to abandon this goal and just depend on the interface-type:

interface IMyInterface
{
    void MyMethod(IMyInterface a);
}

If this insufficient, it is often suggestive of the interface being poorly specified; you should go back to the drawing board and look for an alternative design if possible.

But if you still really need this, you can use a (sort of) C# version of the CRTP:

interface IMyInterface<TSelf> where TSelf : IMyInterface<TSelf>
{
    void MyMethod(TSelf a);
}

and then:

class MyClass : IMyInterface<MyClass>
{
    public void MyMethod(MyClass a) {...}  //implemented from the interface.
}

Note that this is not a completely "safe" solution; there's nothing stopping an evil implementation from using a different type-argument:

class EvilClass : IMyInterface<MyClass>  // TSelf isn't the implementing type anymore...
{
    public void MyMethod(MyClass a) {...}  // Evil...
}

which works against your goal.

Upvotes: 13

Mario
Mario

Reputation: 36487

Simply use IMyInterface instead of MyClass. It will be able to accept anything that is derived from and using that interface. If you don't want this for whatever reason, still do it, but add some other "check" to the interface, something like public bool IsValidParam() or whatever. In general I'd consider something like this bad design (interfaces shouldn't depend on any implementation of that actual interface other than stuff provided in the interface itself).

Upvotes: 0

Related Questions