Suppose a Team class provides:
public int GetScore()
{
return this.score;
}The method produces an integer.
When you call:
team1.GetScore()the call produces that returned integer at the point where the call appears.
One of the clearest ways to use it is to store the result in a local variable.
Consider:
int currentScore = team1.GetScore();Read the statement from right to left.
team1.GetScore()Ask team1 to run GetScore().
If:
team1.score = 3the method sends back:
3int currentScorestores the returned integer.
Conceptually:
team1.GetScore()
↓
returned value 3
↓
currentScore = 3If the method is declared:
public int GetScore()then this is a natural match:
int currentScore = team1.GetScore();The method returns an int.
The local variable stores an int.
For:
int currentScore = team1.GetScore();execution needs the method result before the local variable can receive its value.
The flow is:
call GetScore()
↓
method executes
↓
value returned
↓
initialize currentScoreThe assignment cannot finish until the returning method finishes.
Suppose:
int currentScore = team1.GetScore();After the call completes:
currentScorecontains the integer value returned by the method.
It does not contain:
GetScore()and it does not contain the entire Team object.
It contains the returned result.
Suppose:
team1.score = 3
team2.score = 1Then:
int team1Score = team1.GetScore();
int team2Score = team2.GetScore();can produce:
team1Score = 3
team2Score = 1The same method design executes on different current objects.
The object's state affects the value that is returned.
After:
int currentScore = team1.GetScore();later code in the same scope can use:
currentScoreFor example:
System.Console.WriteLine(currentScore);The method call has already completed.
The local variable now holds the result.
This is valid when GetScore() returns an integer:
int currentScore = team1.GetScore();But a void method such as:
team1.DisplayScore();does not produce a data value to store in an int local variable.
The method's return type determines how the caller can use it.
Suppose execution reaches:
int currentScore = team1.GetScore();A useful trace is:
team1;GetScore() should return;GetScore();this.score;return;currentScore.If:
this.score = 3you should expect:
currentScore = 3after the call completes.
While execution is inside GetScore(), the Call Stack can show that:
GetScore()is currently active above its caller.
When GetScore() finishes, execution returns to the calling method and the returned value becomes available there.
Later activities teach more advanced uses of returned values.
For now:
Do not introduce:
ReturnType localVariable = objectReference.MethodName();Example:
int currentScore = team1.GetScore();Read it as: