A variable declared inside a method is a local variable.
A common pattern is to declare and initialize it in one statement:
int scoreDifference = 2;This statement does two things:
Consider:
double distance = Math.Abs(playerX - ballX);The local variable is:
distanceIts type is:
doubleIts initial value comes from:
Math.Abs(playerX - ballX)The right side is evaluated first.
The result becomes the local variable's initial value.
For example:
int totalScore = homeScore + awayScore;The initialization flow is:
The variable can then be reused later in the same scope.
For example:
double roundedDistance = Math.Round(distance);The Math.Round method produces a numeric result.
That returned value becomes the initial value of:
roundedDistanceYou do not need to redesign the Math method.
You simply use the value it provides.
Initial declaration:
int scoreDifference = 2;Later assignment:
scoreDifference = 4;The first statement creates the local variable and establishes its first value.
The second changes the value of an already-declared variable.
For:
int scoreDifference = 2;the initial value must be compatible with int.
For:
bool shouldDisplay = true;the initial value must be compatible with bool.
For:
string message = "Goal scored";the initial value must be compatible with string.
Suppose:
public void DisplayAdjustedScore(int score)
{
int adjustedScore = score;
}The local variable begins with the current parameter value.
The parameter and local variable remain separate names.
They simply contain equal values at that moment.
For example:
int currentNumber = player1.jerseyNumber;The local variable receives the current field value.
Changing currentNumber later does not automatically change player1.jerseyNumber.
They are separate storage locations.
This:
int temporaryValue = player1.jerseyNumber;is useful only if the method needs a temporary named value for later work.
Do not create extra variables merely to make a simple expression longer.
Use a local variable when its name or reuse makes the method clearer.
A local variable can be used only within its valid scope.
If it is declared inside a method, another unrelated method does not automatically know that local variable.
This is different from a field, which belongs to object state.
Type variableName = initialValue;Read it as:
That starting value may come from: