user164771
user164771

Reputation:

Interfaced function returning type of implementing class

I am looking to implement an interface which has a function which will return the type of the base class without using a generic interface. Is this possible?

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

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

Upvotes: 1

Views: 159

Answers (4)

Chris Missal
Chris Missal

Reputation: 6123

You achieve it like this:

interface IUserService : IService<User>

then your class would be:

class UserService : IUserService

Upvotes: 1

Lou Franco
Lou Franco

Reputation: 89172

Either

  1. You hard code the return type as MyClass

  2. You define the return type as MyInterface and then in the implementation of MyClass you can return a MyClass. The caller won't know what it's getting, but could use typeof to find out.

Upvotes: 0

Gregory Higley
Gregory Higley

Reputation: 16558

If I understand your question correctly, your only choice without generics is to use reflection to do this.

Upvotes: 1

Andrew Hare
Andrew Hare

Reputation: 351516

You would have to do something like this:

interface MyInterface
{
    Type GetBaseType();
}

But at that point it would be simpler to call instance.GetType() since that is what the implementation of this method would most likely look like.

If by "type" you don't mean the reflected type but rather that you wish to be able to use the type from the interface statically at compilation time then you will need to make the interface generic.

Upvotes: 1

Related Questions