first form’s Red button, the event handler makes the first form red but the other forms are unchanged.
The code in the event handler is running in the first form’s instance so that’s the form it affects.
Hopefully by now you think I’ve beaten this topic into the ground and you understand the differ-
ence between the class (
MakeUserForm) and the instance (a copy of MakeUserForm visible on the
screen). If so, you’re ready to learn how to actually display forms.
DISPLAYING FORMS
The new keyword creates a new instance of a form. If you want to do anything useful with the form,
your code needs a way to refer to the instance it just created. It can do that with a variable. I’m jump-
ing the gun a bit by discussing variables (they’re covered in detail in Lesson 11) but, as was the case
when I introduced the
if statement in Lesson 8, this particular use of the concept is very useful and
not too confusing, so I only feel a little guilty about discussing it now.
To declare a variable to refer to a form instance, you enter the form’s type followed by whatever
name you want to give the new instance. For example, the following code declares a variable named
newUserForm of type MakeUserForm:
MakeUserForm newUserForm;
At this point, the program has a variable that could refer to a MakeUserForm object but right now it
doesn’t refer to anything. At this point the variable contains the special value
null, which basically
means it doesn’t refer to anything.
To make the variable refer to a form instance, the code uses the
new keyword to create the instance and
then sets the variable equal to the result. For example, the following code creates a new
MakeNewUser
form and makes the
newUserForm variable point to it:
newUserForm = new MakeUserForm();
Now the variable refers to the new form. The final step is to display that form. You can do this by
calling the new form’s
ShowDialog or Show method.
Technically the variable doesn’t hold or contain the form. Instead it contains a
reference to the form. The reference is like an address that points to where the
form really is in memory. When your code says something like
newUserForm
.Show()
, it hunts down the actual form instance and invokes its Show method.
For now the distinction is small and you don’t need to worry too much about it,
but later it will be useful to know that some variables are value types that actu-
ally hold their values (
int, long, double) and some are reference types that hold
references to their values (object references and interestingly
string).
Lesson 17 says a bit more about this when it discusses structures.
596906c09.indd 105 4/7/10 12:32:18 PM