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.
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.
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.
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.jerseyNumberThe field belongs to the object.
The parameter belongs to one method call.
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.
Inside:
this.jerseyNumber = number;this.jerseyNumber clearly identifies the object's field.
number identifies the method parameter.
Read the line as:
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;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.
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:
When you see a name in C#, ask:
That helps determine where it can be used and what role it serves.