Mikhail Sokolov
Mikhail Sokolov

Reputation: 556

using base class in interface

I have one base class:

class BaseClass{ }

I want to implement interface, that uses base class:

public interface IClass
{
   BaseClass GetValue();
}

and then create child classes, that implemented this interface, but in method returned thier own type of class:

class Child: BaseClass, IClass
{
   Child GetValue(); 
}

How can I do that correctly?

Upvotes: 2

Views: 74

Answers (2)

PMF
PMF

Reputation: 17185

That's not so easy. The way you would expect it to work doesn't because any class implementing IClass must exactly implement the method from the interface (If you've got an instance of IClass, how would you know that the static type returned by GetValue() is Child? There are workarounds using Generics, but they may be not so nice to use, i.e.

 public T GetValue<T>();

where you can exactly specify the type you want to have returned. This, however, may get really ugly if used in combination with virtual overloads. Another alternative is creating a new implementation:

class Child: BaseClass, IClass
{
    BaseClass IClass.GetValue(); 
    new Child GetValue();
}

Like this, you get a BaseClass if the static type of the object in the call is IClass and a Child if it is statically a Child.

Remember that

IClass a = new Child();
Child b = a.GetValue(); // Error: Cannot convert BaseClass to Child

will never work, since the static return type of IClass.GetValue() is BaseClass.

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

Use generics:

public interface IClass<T> where T : BaseClass
{
   T GetValue();
}
class Child: BaseClass, IClass<Child>
{
   Child GetValue(); 
}

Upvotes: 4

Related Questions