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.
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:
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:
and then:
Note that this is not a completely “safe” solution; there’s nothing stopping an evil implementation from using a different type-argument:
which works against your goal.