1.5.11 Writing and Using Return Statements in C#

Video: Accepting Return Values from Methods (15:27)
A Returning Method Sends a Value Back to Its Caller

A method with a non-void return type produces a value.

public int GetScore()
{
    return this.score;
}

The keyword:

return

sends a value back to the code that called the method.

Match the Return to the Declared Type

In:

public int GetScore()

the return type is:

int

Therefore:

return this.score;

must produce an integer-compatible value.

The method declaration tells the caller what kind of result to expect.

Return a Field

Suppose Team contains:

public int score;

A simple getter-style method can be:

public int GetScore()
{
    return this.score;
}

Read it as:

Return a Local Variable

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 result
Return a Calculation Directly

The 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.

The Caller Can Store the Result

Given:

public int GetScore()
{
    return this.score;
}

the caller can write:

int currentScore = team1.GetScore();

Conceptually:

team1.GetScore()
      ↓
return score
      ↓
currentScore
return Is Not the Same as Displaying

This 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.

return Is Not Assignment

This changes object state:

this.score = 3;

This sends the current value to the caller:

return this.score;

Those operations have different purposes.

Return a Compatible Numeric Result

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.

A Simple Return Ends the Current Method

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.

Current Learning Boundary

Later activities teach:

  • returns inside more complex conditional paths;
  • methods that must return on every path;
  • multiple or early returns.

For now, write one clear return statement that matches the declared return type.

Key Pattern
public ReturnType MethodName()
{
    ReturnType result = ....;

    return result;
}

The method determines a result and sends it back to the caller.