Inheriting a from with a special constructor

G

Guest

Hi,

I created a base form, what holds several graphical elements (text boxes,
etc). This form has only one constructor, what expects one integer
parameter. Call this BaseForm
It's constructor looks like:
public BaseForm(int Param1)
{
InitializeComponent();
}
Now I inherit a second form from this one (Call this InheritedForm), and I
found out, that I have to define the constructor as follows:
public InheritedForm(int Param1):base (Param1)
{
InitializeComponent();
}
Now, my problem is, that in the designer the form can not be shown, since
there is an error:
Construcotr on type 'WindowsApplication1.BaseForm' not found.

Why? I defined the constructor! Moreover, if I create a second "default"
conrtuctor:
public BaseForm()
{
InitializeComponent();
}
is not helping at all.

How can I see in the designer the InheritedForm? How can I add more visual
components on it? What did I wrong?

Thanks:

Peter
 
S

Stoitcho Goutsev \(100\)

Peter,



Fist the reason why you need to re-declare the constructor: This is because
when you declare this specialized constructor the C# doesn't generate the
default one for you. (If you don't declare any constructor at all C#
declares one default for you) When the inherited form is instantiated its
constructor tried to call the base constructor; this is the way types are
instantiated - each type in the hierarchy needs to have its constructor
called. You don't specify which constructor exactly to call, so it tries to
call the default one, which is not declared and you get the error.



You don't have to re-declare the exact constructor you can declare different
one as long as you call one of the base class's constructors.



Example:



public InheritedFrom(string name): base(1)

{

.....

}



Now about the designer error: When you open a form for design the designer
creates an instance of the base-form class (not the one that you are going
to design). In order to create it, the base form has to declare a
parameterless constructor. This is the constructor the designer uses. In
your case you can design your BaseForm because it derives from Form that has
this constructor and the designer actually instantiates object of the Form
class (not BaseForm). When you try to derive from BaseForm you cannot design
the new form because the designer cannot instantiate BaseFrom (no default
constructor).



Adding default constructor to the BaseForm is going to help. The only think
that you need to do is to close the designer window in VS (clicking on its X
button), maybe is a good idea to recompile the project and then open it
again.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top