Public, Private, and Unspecified Classes

 

Demonstrations

Demo #1: Initializing an Integer

This project is initially set up so an integer intNumber is declared in line CP011. However, it is not assigned a number until the program reaches line CP103 in event handler button1_Click.

  1. Do not click on the Start Demo button on the main window this first time. Instead, click directly on the Call Child Window button. This should produce a message box with the message shown in Figure 6-3.

    image from book
    Figure 6-3: Message box #1

    This message comes from line CP603 in Form 2, Form2_Load. CP603 has the value 0 for intAnswer, which it received from CP602. CP602 got the 0 from frmParent.intNumber. intNumber is declared in Form1 at line CP011. But who put the value 0 in intNumber? The compiler.

    The message box appears before the child window appears because any code executed in FormX_Load always executes before its window is displayed. When you click on the OK button in the message box, the child window appears and is created.

  2. Click on the OK button to remove message box #1, then click on the Return button to exit the child window.

  3. When the main window appears, click first on the Start Demo button, then on the Call Child Window button. The message box appears again, but this time the value of intNumber is 92.

    image from book
    Figure 6-4: Message box #2

    This time there is no mystery about the new intNumber value of 92. The variable was assigned the number 92 in line CP103 in event handler button1_Click, which is the Start Demo button.

  4. Click on the OK button in message box #2, then on the Return button to close the child window. Next, click on Quit to close the project.

    So we conclude that if you declare an integer in the class (line CP011) and forget to assign it a number, then the compiler will placea0inthat location to keep your program running. This is fine, but it only works with integers. The compiler will not place its own default numbers or characters in string or char arrays, float, double, etc.

  5. In the IDE, press the F7 key to display the Form1 source code. Change line CP011 from public int intNumber; to public int intNumber = 6; . This assigns an initial value to this variable.

  6. Recompile and rerun the program two more times. The first time, move directly to the Call Child Window button, which produces the message intNumber from Form 1 = 6. The second time, click on Start Demo followed by Call Child Window . This time the MessageBox answers intMessage from Form 1 = 92 since you initialized intNumber in line CP011.

  7. Is it necessary to place the word public in front of the declaration in line CP011? Move to line CP011 and delete the word public. Then recompile and rerun. What happens?

    You immediately get a compiler error when you attempt to compile, because you cannot pass information between windows unless that information (variable intNumber) is declared as a public member of a class. It is listed in the class listing, but it has to have the designation public to make it a candidate for access by other windows (the child window).

  8. Leave line CP011 as it is (with the word public deleted), and move to Form2.cs and lines CP602 and 603. Comment out these two lines so they are no longer executable. The lines should look like this:

     /* CP602 */      // int intAnswer = frmParent.intNumber; /* CP603 */      // MessageBox.Show("intNumber from Form1 = "                  // + intAnswer.ToString() + " ."); 

    Recompile and rerun.

    Why did the project run correctly this time? In the first case, the compiler saw that variable intNumber was supposed to be passed to Form2, but you cannot pass a variable that is not a public member of the Form1 class. So the compiler balked. But in the second case, the variable was not required by Form2, and Form2 did not ask for frmParent.intNumber (since you had commented out lines CP602-CP603) and the project ran OK.

1.  

Can you switch the designation public in line CP011 to private and still pass the variable to Form2? Try this. Remove the comment forward slashes on lines CP602-CP603, and replace int intNumber = 6; in line CP011 with private intNumber = 6; . Will this combination compile?

image from book

Answers

1.  

No. Only a public member can be passed to another window. Change the private designation in line CP011 back to public.

Demo #2: Creating a Variable That Is Global to Form1

  1. In line CP012, remove the double forward slashes in front of this declaration:

     int intGlobalNumber = 77; 
  2. In line CP104 in the Form 1 button1_Click event handler, remove the double forward slashes from this message box:

     /* CP104 */      MessageBox.Show("intGlobalNumber = "                  + intGlobalNumber.ToString()+ " ."); 

    Recompile the program and rerun. Does the message box have access to intGlobalString? Yes. As soon as you click on the Start Demo button, the message box shown in Figure 6-5 appears.

    image from book
    Figure 6-5: Message box #3

    So we conclude that you can create variables that are global to a given form by listing them in the class list at the top of the *.cs file, and it doesn t matter whether or not they are declared as public. Interestingly enough, a variable that is undeclared (with neither public or private) reverts to a private variable ” one that can only be used within the confines of this form.

    But what if we declare intGlobalNumber somewhere else, like in the public Form1 area just above or below the InitializeCom-ponent() statement?

  3. Cut the statement int intGlobalNumber = 77; from line CP012 and paste it at line CP016. Recompile.

    Does this work? The answer is no. Integer intGlobalNumber has to be declared under the public class Form1 listing (CP010) to become a global variable (but it needs no public designation unless it is needed by another window form).

1.  

Is line CP016 not a part of the public class Form1 listing?

image from book

Answers

1.  

By placing the statement in the CP016 slot, which is inside the curly brackets of public Form1(), we defeat this declaration; it is inside the public Form1() curly brackets! As long as int intGlobalNumber = 77 remains within the curly brackets at CP016, it is not a good declaration.

  1. Move int intGlobalNumber = 77; from line CP016 back to CP012, where it belongs. Now the compiler will recognize this declaration. Is there any other place we can put int intGlobalNumber = 77 and have the compiler recognize this declaration?

  2. Cut line CP012 (int intGlobalNumber = 77;) and move it down to line CP099 (which is an open space between the static main procedure and the first event handler, button1_Click, at line CP101). Having placed this statement at CP099, is this an acceptable global declaration?

Yes, this works. But why does it work? Because this particular declaration, int intGlobalNumber = 77; , can occupy a space at either CP012 or CP099 (but not both). CP099 is simply a continuation of the partial class Form1 declaration that begins at line CP010. In either location the designation public or private is not required (but it defaults to a private declaration).

If this declaration works properly at line CP012 or CP099, why won t it work within the public Form1() function at line CP016? Because public Form1() is a function, not a declaration. This same statement, int intGlobal , would not work properly in any of the functions described in the class, including protected void override Dispose() and private void InitializeComponent().

So what purpose does public Form1() serve (besides containing the procedure InitializeComponent())? To answer this question we pull some code from an old demonstration project named TimerTimer.

 XT016:      public Form1()             { XT017:        Timer timer = new Timer();               // Next line: 1,000 milliseconds between ticks, or 1 per second. XT018:        timer.Interval = 1000; XT019:        timer.Tick += new EventHandler(timer1_Tick); XT020:        timer.Start(); // Alternate statement is 'timer.Enabled = true;'. XT021:        InitializeComponent(); XT022:      } 

As it turns out, the programmer could just as well have created an event handler in the TimerTimer project named Form1_Load, and placed these lines of code (XT016-020) into that handler. The Form1_Load handler executes just as soon as the main window is created, so the timer would be started there. Therefore, one of the purposes of public Form1() in the middle of the class declaration is to perform the same initializing functions that Form1_Load handles.

1.  

Can the call to execute the InitializeComponent() function just above line CP016 be placed anywhere except where it is (for example, in a Form1_Load function)?

no, you must leave the initializecomponent() exactly where it is!

Answers

1.  

No, you must leave the InitializeComponent() exactly where it is!

To create the Form1_Load() method (subroutine), move to the Form1 window and highlight it (to place its properties in the Properties window). At the top of the Properties window, click on the Events icon to bring up the event handlers. Under Behavior, find Load, and double-click on it. This places the Form1_Load() method into the Form1 source code.

Some programmers abhor the FormX_Load event handler so they place all the startup information in the public FormX() function at the top of the file. The project works fine either way.

If you are like most programmers, you become annoyed when you expect a variable in a project to be available to you at the point at which you are currently working, and the compiler gives you one of those cannot identify errors concerning that variable. This means that the declaration of that variable has to be moved to a point within the top-level class declaration. If the variable is not needed by other windows (forms), then it need not be declared as public, but it should be moved to the top of the form to ensure that it is available to all elements within the form. If you declare the variable as neither public nor private, it reverts to a private variable. By top of the form, we mean precisely one location:

 partial class FormX  : Form {   // RIGHT HERE !! //   public FormX()   {     InitializeComponent();   etc. 

Your code will be easier to read if you place all the declarations together, as shown above.

 


Unlocking Microsoft C# V 2.0 Programming Secrets
Unlocking Microsoft C# V 2.0 Programming Secrets (Wordware Applications Library)
ISBN: 1556220979
EAN: 2147483647
Year: 2005
Pages: 129

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net