Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Form that inherit Abstract class AND implements interface.

I need to have a multiple Form classes in my project. So was thinking about putting everything those forms will have in common, together in abstract class. This class will have inheriet Form class and also an interface. Sth like that:

public interface IMyForm
{
void Init();
}

public abstract class AMyForm : Form, IMyForm
{
    void IBrowser.Init()
    {
        throw new NotImplementedException();
    }     
}

public partial class MainClass : AMyForm 
{

// But here the warning is shown (That i have to add override keyword),
// but when i do, The error is shown that i cannot override from non abstract thing 
    public void Init() 
    {
    }
}

Could u tell me how to achieve that ?

like image 436
Marshall Avatar asked Dec 02 '22 22:12

Marshall


1 Answers

While Jon Skeets answer is correct for general programming, I would advise AGAINST using abstract classes on Forms and User controls. First issue is, that designer won't be able to create an instance of the abstract class and thus will not be able to display a form that inherits FROM the abstract form in the designer. Meaning that you will not be able to add new controls to form via designer, unless - as suggested in comments below - you add a surrogate class that implements the abstract class and is then used as a base for other inherited forms, e.g.: AbstractMyForm -> MyFormSurrogate -> MyForm.

Second and larger issue is in my opinion, that this means that you are trying to stick logic into forms. This is usually not desired, especially if you end up coupling your business logic to your display technology, in this case Winforms. My advice would be to try to use the Model View Presenter pattern to separate as much logic as possible in ordinary classes (using abstract classes, interfaces, etc.) and then data bind them to the form. If there are visual parts that are shared (e.g.: a group of checkboxes), make user controls for such parts and just reuse them on forms.

I hope I didn't presume too much of your knowledge of working with winforms, but I had similar questions when I started getting into GUI development.

like image 173
Rok Avatar answered Dec 16 '22 11:12

Rok