Creating new Forms

W

WRH

Hello
This is not a problem but rather curiosity on my part. If I have
a Form, say Form1, with button controls and a variable,
say public int x, then replicate it as per Form frm = new Form1()
then x is not not part of frm, although the button controls are.
If I replicate as per Form1 frm = new Form1() then frm has
x.
 
O

Octavio Hernandez

Hi,

In both cases:

Form frm = new Form1()

and

Form1 frm = new Form1()

you are constructing and object of the Form1 class, and the instance DOES
have the 'x' member.

But in the first case, you're assigning the reference to the created to
object to a variable of type Form, which is the ancestor of Form1. This is
perfectly valid because of the inheritantance relationship, and this
possibility can be useful if you wanted to manipulate your Form1 object as a
generic Form, without referring to it's specific features (like x or the
button controls).

In both cases, the object the variable frm points to is of type Form1. If
you used the first statement, you can anyway refer to the 'x' member of the
object using a type cast:

int n = ((Form1) frm).x; // indicate the compiler that 'frm' points to a
Form1 object

OR

int n = (frm as Form1).x;

Hope this helps.

Regrards - Octavio
 
M

Morten Wennevik

Hi WRH,

A Form does not have a x variable, but it does have a Controls collection, which in turn holds your buttons.
To access the x variable from your Form object cast it to Form1

Form frm = new Form1();
Form1 frm1 = (Form1)frm;
 

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