Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid error "Constructor on type 'MyType' not found" when inheriting a base class

I have a Visual Studio 2010 Windows Forms app which includes a Form base class that other classes will inherit. The base class' constructor takes a parameter that the child classes will pass to the base class.

Example:

public partial class BaseForm : Form {     public BaseForm(int number)     {         InitializeComponent();     } }  public partial class ChildForm : BaseForm {     public ChildForm(int number)         : base(number)     {         InitializeComponent();     } } 

The problem that I'm running into is, when I attempt to open the ChildForm in VisualStudio's Design View mode, I receive the following error:

Constructor on type 'MyProject.BaseForm' not found.

Note: regardless of the error, the project compiles and runs fine.

I can avoid the error if I overload the constructor with one that does not contain any parameters.

Example: (This gets rid of the error)

public partial class BaseForm : Form {     public BaseForm(int number)     {         InitializeComponent();     }      public BaseForm()     {         InitializeComponent();     } }  public partial class ChildForm : BaseForm {     public ChildForm(int number)         : base(number)     {         InitializeComponent();     } } 

My question is, how can I create a base class that does not include a parameterless constructor and avoid the Design View error?

like image 408
Jed Avatar asked May 01 '13 20:05

Jed


People also ask

Is it possible to inherit the constructors of its base class?

In inheritance, the derived class inherits all the members(fields, methods) of the base class, but derived class cannot inherit the constructor of the base class because constructors are not the members of the class.

What is a Parameterless constructor?

A constructor that takes no parameters is called a parameterless constructor. Parameterless constructors are invoked whenever an object is instantiated by using the new operator and no arguments are provided to new . For more information, see Instance Constructors.


1 Answers

That is completely impossible.

The form you see in the design view is an actual instance of your base class.
If there is not default constructor, the designer cannot create that instance.

You can mark the constructor with the [Obsolete("Designer only", true)], and make it throw an exception if called when not in the designer, to prevent other people from calling it.

like image 83
SLaks Avatar answered Oct 11 '22 02:10

SLaks