Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reimplementation of inherited interface methods

I did not fully understand using Interfaces, so I have to ask :-)

I use a BaseClass, which implements the IBaseClass interface.These interface only contains one declaration :

public interface IBaseClass
{
    void Refresh ();
}

So I have implement a Refresh method in my Baseclass :

    public void Refresh ()
    {
        Console.WriteLine("Refresh");
    }

Now I want to use some classes which extends from these Baseclass and implements the IBaseClass interface :

    public class ChildClass : BaseClass,IBaseClass
    {
    }

But cause of the implementation of "Refresh" into my BaseClass I does not have to implement the method again. What should I do, to force the implementation of "Refresh" into all childs of BaseClass as well as all childclasses of childclass.

Thanks kooki

like image 391
Kooki Avatar asked Dec 16 '22 16:12

Kooki


2 Answers

You cannot force derived classes to re-implement the method in the way that you have specified. You have three options:

  1. Do not define refresh in the base class. The interface will force child classes to implement it.
  2. Eschew the interface if its only purpose was to force implementation and declare the base class as abstract as well as refresh, for which you would not give an implementation.
  3. Define refresh in the base class as virtual. This allows overrides but will not force them. This is how ToString() works.

This is all assuming that your base class is larger than a single method. If indeed your code is exactly what you posted then Oded's answer is the best choice.

like image 169
Levi Botelho Avatar answered Dec 18 '22 05:12

Levi Botelho


Simple. Don't supply a base class implementation, and you will have to implement the method in every inheriting class.

One way to achieve that is to make BaseClass abstract:

public abstract BaseClass : IBaseClass
{
    public abstract void Refresh();
}
like image 36
Oded Avatar answered Dec 18 '22 06:12

Oded