View Single Post
Old 12-14-2006, 12:07 AM
MikeJ's Avatar
MikeJ MikeJ is offline

Retired Moderator
* Expert *
Join Date: Sep 2002
Location: Austin, Texas
Posts: 6,747
Default A Note on Variable Scope

What about that "Private Sub MessageUser()" line from our previous example? It's a private sub, as the name states, but try to access it from outside the Vehicle class. In the MainForm_Load() sub, try adding Van.MessageUser. You should get a build error that states 'Vehicle.Private Sub MessageUser()' is not accessible in this context because it is 'Private'. Try the same thing with the _VehicleType variable and you should get a similar result.

As the error suggests, you can't access certain types of class members from outside of the class itself.

The four types of variables we have used so far are:
Public variables. These can be access directly from the class. We choose not to use this with OP by convention. Rather we create Properties (we'll get into this later) to adjust variables directly, or use Get/Set methods.

Private variables. These can be accessed only within the class. Private variables cannot be accessed by any subclasses or other class. These are ideal whenever you have a class you know will not be inherited. Also, these are good for storing data that should not be exposed publicly.

Protected variables. These can be accessed by the class or any subclass that is inherited. These are what I personally use because if you design a subclass later, you don't have to change your base class code later. This is a good catchall private storage method.

Local variables. These are created by the Dim statement. These exist for the duration of the location in which they are declared. For example, if you Dim x As Int32 in Form_Load(), it will only exist in the Form_Load() method.

These four access types are also used frequently in sub/function/property headings, and thus are not limited to just variables. For more information on access types, see the MSDN article.
{ Lex Fori } { Locus Classicus } { Rutilus Scrinium }
Osculare pultem meam!
Reply With Quote