1.4.12 Variable Scope

Scope Describes Where a Name Can Be Used

A name in C# is not automatically available everywhere in the program.

Scope describes the region of code where a particular name can be used.

In Module 1.4, this becomes important because parameters exist only within the method that declares them.

A Parameter Is Scoped to Its Method

Consider:

public void SetJerseyNumber(int number)
{
    this.jerseyNumber = number;
}

The parameter number can be used inside the body of SetJerseyNumber.

Outside that method, another method cannot automatically use the same number parameter.

The Same Parameter Name Can Appear in a Different Method

Consider:

public void SetJerseyNumber(int number)
{
    this.jerseyNumber = number;
}

public void DisplayNumber(int number)
{
    System.Console.WriteLine(number);
}

Each method has its own parameter named number.

They are separate parameter variables because they belong to separate method scopes.

Fields Have a Different Scope

Suppose the class contains:

public int jerseyNumber;

Methods in the same object can access that field according to the field's access rules.

Inside instance-level code, you can make that relationship explicit with:

this.jerseyNumber

The field belongs to the object.

The parameter belongs to one method call.

Compare Field Scope and Parameter Scope
class Player
{
    public int jerseyNumber;

    public void SetJerseyNumber(int number)
    {
        this.jerseyNumber = number;
    }
}

The field jerseyNumber is part of every Player object's state.

The parameter number exists only while SetJerseyNumber is active for a call.

Scope Helps Explain Why this Clarifies Meaning

Inside:

this.jerseyNumber = number;

this.jerseyNumber clearly identifies the object's field.

number identifies the method parameter.

Read the line as:

Local Names Do Not Become Object State Automatically

A method parameter can hold a value during the method call.

That value does not automatically become a field on the object.

The method must explicitly assign it if the value should become part of object state:

this.jerseyNumber = number;
Scope Is About Name Visibility

Suppose the argument 7 is passed to the parameter number.

The value 7 can appear in many places.

Scope is about the name number, not about whether the quantity 7 exists elsewhere.

Local Variables Are Another Scoped Name

C# also allows variables declared inside methods.

Those are commonly called local variables.

Detailed local-variable creation and initialization are taught later in Module 1.4.

For now, recognize the general rule:

The Main Scope Question

When you see a name in C#, ask:

That helps determine where it can be used and what role it serves.