A method with a return type such as double promises to send a value of that type back to its caller. Inside the method, return supplies the value and ends that invocation of the method.
For the Zoo's Animal class, the animal can calculate the portion it needs from its own fields:
public double GetPortionSize()
{
double portion = this.Weight * this.PortionSizePercentage;
return portion;
}The caller can store the returned number:
double foodWeight = this.ComoZoo.FeaturedAnimal.GetPortionSize();The expression after return supplies the result; the method header declares its type. Here, both the calculated portion and the declared return type are double.
The call first enters GetPortionSize() on the featured Animal object. The method calculates portion using that object's fields. return portion; sends the number back to the call site, where the assignment stores it in foodWeight. The local variable portion itself belongs to the method and is not passed back as a variable.
A Zoo Guest can ask its Wallet to remove money, then pass the actual amount back to the code that called Guest:
public decimal RemoveMoney(decimal amount)
{
decimal amountRemoved = this.Wallet.RemoveMoney(amount);
return amountRemoved;
}If the wallet removes only 0.20m from a request for 0.53m, Guest returns 0.20m. Returning the requested amount instead would incorrectly tell the caller that the full payment was made.
A void method has no value to send back. It can finish by reaching its closing brace. It can also use return; to stop immediately:
public void ShowStatus(string status)
{
if (status == null)
{
return;
}
MessageBox.Show(status);
}The return; here ends the method without producing a string. A method declared decimal or double needs a return value of the declared type when it completes.
Read the method header to find the promised type, read the expression after return to find the value sent back, and inspect the caller to see how that value is used. Later pages examine methods with several possible return paths.