
168
LESSON 13 Understanding scope
For example, suppose you build a Person class with a private field named Salary. Not only can all
of the code in an instance see its own
Salary value, but any Person object can see any other Person
object’s
Salary value (assuming it has a reference to another Person object).
In fact, declaring fields to be public is bad programming style. It’s better to
make a public property instead. Lesson 23 explains why and tells how to make
properties. Public fields do work, however, and are good enough for this discus-
sion of accessibility.
RESTRICTING SCOPE AND ACCESSIBILITY
It’s a good programming practice to restrict a field’s or variable’s scope and accessibility as much as
possible to limit the code that can access it. For example, if a piece of code has no business using a
form’s field, there’s no reason to give it the opportunity. This not only reduces the chances that you
will use the variable incorrectly, but it also removes the variable from IntelliSense so it’s not there to
clutter up your choices and confuse things.
If you can use a variable declared locally inside an event handler or other method, do so. In fact, if you
can declare a variable within a block of code inside a method, such as in a loop, do so. That gives the
variable very limited scope so it won’t get in the way when you’re working with unrelated code.
If you need multiple methods to sha ...