What exactly does a return statement do in C#?
Solution 1
Return will exit the function when calling it. Whatever is below the return statement will thus not be executed.
Basically, return
indicates that whatever operation the function was supposed to preform has been preformed, and passes the result of this operation back (if applicable) to the caller.
Solution 2
Return
will always exit (leave) the function, anything after return will not execute.
Return example:
public int GivePoints(int amount)
{
Points -= amount;
return; //this means exit the function now.
}
Return a variable example:
public int GivePoints(int amount)
{
Points -= amount;
return amount; //this means exit the function and take along 'amount'
}
Return a variable example and catch the variable that got returned:
public int GivePoints(int amount)
{
Points -= amount;
return amount; //this means exit the function and take along 'amount'
}
int IamCatchingWhateverGotReturned = GivePoints(1000); //catch the returned variable (in our case amount)
Solution 3
return
will return control from the current method to the caller, and also pass back whatever argument is sent with it. In your example, GivePoints
is defined to return an integer, and to accept an integer as an argument. In your example, the value returned is actually the same as the argument value.
A returned value is used from somewhere else in your code that calls the defined method, GivePoints
in this example.
int currentPoints = GivePoints(1);
would mean that currentPoints
gets assigned the value of 1.
What this breaks down to is that GivePoints
is evaluated. The evaluation of GivePoints
is based on what the method returns. GivePoints
returns the input, thus, GivePoints
will evaluate to 1 in the above example.
Mikey D
Updated on March 29, 2020Comments
-
Mikey D about 4 years
It's hard for me to grasp what exactly a return statement is doing. For instance, in this method...
public int GivePoints(int amount) { Points -= amount; return amount; }
Even if I place any random integer after return, the GivePoints method still does the exact same thing. So what is it that the return statement is doing?
-
danludwig about 11 years+1 Another good thing to mention might be the
Stack
concept: that methods are invoked on a stack, and areturn
statement exits the current method, returning control flow (and usually a value) back to the previous method on the stack. -
Heather about 11 yearsAlso, no code that appears after the return statement is run will be evaluated. That's why your "random integer" value is ignored.
-
Ron almost 7 yearsYou should've explained that anything after return will not execute, which seems to be the questioner's true conundrum.
-
M.M almost 3 yearsThe first example should fail to compile (function must return int value)