A local variable is declared inside a method or block.
It exists to support the work being performed in that scope.
For example:
public void DisplayScoreDifference()
{
int homeScore = 3;
int awayScore = 1;
int difference = homeScore - awayScore;
System.Console.WriteLine(difference);
}The variables:
homeScore
awayScore
differenceare local to this method.
Compare:
public int score;inside a class with:
int difference = homeScore - awayScore;inside a method.
The field is part of an object's state.
The local variable supports the current method execution.
That distinction affects:
Suppose a method needs to calculate an average:
double averageGoals = (double)totalGoals / gamesPlayed;The local variable:
averageGoalsgives the result a meaningful name.
The method can then use it later:
System.Console.WriteLine(averageGoals);A local variable can make multi-step calculations easier to read.
For example:
bool isGoalkeeper = player1.position == "Goalkeeper";Now:
isGoalkeepercontains the result of the comparison.
That value can be used by an if statement:
if (isGoalkeeper)
{
System.Console.WriteLine("Goalkeeper selected.");
}The local variable stores method-level decision information.
Suppose:
Team currentTeam = player1.team;The local variable:
currentTeamnow holds a Team reference.
This does not create another Team object.
It stores a reference to the object already reached through player1.team.
More detailed shared-reference behavior is taught later.
For now, recognize that local variables can hold class-type references as well as simple values.
The method must establish a local variable before later statements can use its name.
For example:
int difference = homeScore - awayScore;
System.Console.WriteLine(difference);The declaration comes before the use.
Consider:
public void DisplayDifference()
{
int difference = 2;
}Another method cannot simply write:
System.Console.WriteLine(difference);and expect to use that local variable.
The name belongs to the scope where it was declared.
For example:
int score = 1;
score = 2;The local variable is still the same local variable.
Its current value changed.
This is similar to field assignment, but the storage belongs to the method scope rather than object state.
Suppose a Player needs to remember its jersey number after a method finishes.
That information belongs naturally in a field such as:
public int jerseyNumber;A temporary local variable alone would not represent the Player's continuing state.
Ask:
That question often helps distinguish field from local variable.
Examples of useful local-variable purposes include:
Do not promote every temporary value into a field.
When execution pauses inside a method, Visual Studio can display local variables and their current values.
That helps you trace:
CO-042 adds more focused debugging of parameter values and Boolean expressions.
Keep this relationship clear:
Fields
All three can have names and values.
Their roles and scopes are different.