1

I have an interface resembling this:

interface IMyInterface<T>
{
    void MyFunction(T myParam);
}

However it is designed to be used in such a way that T will always be the implementing class, like such:

class MyClass : IMyInterface<MyClass>
{
    ...
}

Is there a way to reference the implementing class within the interface definition without this template declaration? It seems like there should be something, but I can't find any information on it.

Shane Duffy
  • 1,117
  • 8
  • 18
  • You can do `where MyClass : IMyInterface`, but that's a very tricky constraint to employ, and I'm not sure there's as much value in it for an interface as there is for an abstract base class. It's not something you use unless you've exhausted all other options. – madreflection Feb 25 '20 at 23:42
  • I am currently using a template like I described above, and employing `where MyClass : IMyInterface` in functions where the templates are defined from the the interface, and it works completely fine. I'm more curious about whether there is a syntactically better way to achieve this. – Shane Duffy Feb 25 '20 at 23:52
  • 1
    https://learn.microsoft.com/en-us/archive/blogs/ericlippert/curiouser-and-curiouser – Servy Feb 25 '20 at 23:54
  • [Here's a very similar SO question about Java](https://stackoverflow.com/q/7354740/120955). The answers are relevant to C# as well. – StriplingWarrior Feb 25 '20 at 23:56
  • I think your C++ background might be working against you here. Discard the word "template" when working with C#. Generics work differently. If you can show a [mre] of what you need, someone might be able to show you how to do it in C#. Right now, the purpose is a little vague. – madreflection Feb 25 '20 at 23:58
  • Thanks Servy, that answers my question. – Shane Duffy Feb 25 '20 at 23:58
  • To start with *Template* is the wrong terminology, this is a *generic interface*. Secondly this a sticky question in general and relies on the fact you have added all the information, and that this is not XY – TheGeneral Feb 25 '20 at 23:58

0 Answers0