A method with a non-void return type produces a value.
public int GetScore()
{
return this.score;
}The keyword:
returnsends a value back to the code that called the method.
In:
public int GetScore()the return type is:
intTherefore:
return this.score;must produce an integer-compatible value.
The method declaration tells the caller what kind of result to expect.
Suppose Team contains:
public int score;A simple getter-style method can be:
public int GetScore()
{
return this.score;
}Read it as:
A method can calculate a result first:
public int GetTotalGoals()
{
int totalGoals = this.homeGoals + this.awayGoals;
return totalGoals;
}The flow is:
calculate value
↓
store in local variable
↓
return local variable
↓
caller receives resultThe same result can be returned without an intermediate local variable:
public int GetTotalGoals()
{
return this.homeGoals + this.awayGoals;
}C# evaluates the expression first, then sends the resulting integer back.
Given:
public int GetScore()
{
return this.score;
}the caller can write:
int currentScore = team1.GetScore();Conceptually:
team1.GetScore()
↓
return score
↓
currentScoreThis displays:
System.Console.WriteLine(this.score);This returns:
return this.score;Displaying information sends it to an output surface.
Returning information sends it to the caller.
This changes object state:
this.score = 3;This sends the current value to the caller:
return this.score;Those operations have different purposes.
Suppose a method returns double:
public double GetAverageGoals()
{
double average = (double)this.totalGoals / this.gamesPlayed;
return average;
}The returned local variable matches the method's declared type.
When execution reaches:
return this.score;the value is sent back and execution resumes in the caller.
For CO-045, use straightforward methods with one clear return at the normal end of the method.
Later activities teach:
For now, write one clear return statement that matches the declared return type.
public ReturnType MethodName()
{
ReturnType result = ....;
return result;
}The method determines a result and sends it back to the caller.