Compatible function that returns the type of the implementing class

I'm looking to implement an interface that has a function that will return the type of the base class without using a generic interface. Is it possible?

class MyClass : MyInterface<MyClass> // Would rather use one below

class MyClass : MyInterface   // Functions already know to use MyClass

      

+2


source to share


4 answers


If I understand your question correctly, your only non-generic choice is to use reflection for this.



+3


source


You would need to do something like this:

interface MyInterface
{
    Type GetBaseType();
}

      



But at this point it would be easier to call instance.GetType()

, as it will be similar to the implementation of this method.

If by type you don't mean a reflected type, but rather want you to be able to use that type from an interface statically at compile time, you need to make a generic interface.

+2


source


Or

  • You arbitrarily write the return type as MyClass

  • You define the return type as MyInterface, and then in your implementation of MyClass, you can return MyClass. The caller won't know what he is getting, but can use typeof to find out.

+1


source


You reach it like this:

interface IUserService : IService<User>

      

then your class will be:

class UserService : IUserService

      

+1


source







All Articles