What exactly does the return statement do in C #?

It’s hard for me to understand what exactly the return statement does. For example, in this method ...

public int GivePoints(int amount) { Points -= amount; return amount; } 

Even if I put any random integer after the return, the GivePoints method still does the same. So what does the return statement do?

+4
source share
5 answers

The return will exit the function when it is called. Thus, anything below the return statement will not be executed.

Basically, return indicates that any operation that the function was supposed to preform was preformed and passes the result of this operation back (if applicable) to the caller.

+3
source

return will return control from the current method to the caller, and also pass back any argument with it. In your example, GivePoints is defined to return an integer and accept the integer as an argument. In your example, the return value actually matches the value of the argument.

The return value is used from another code in your code that calls the given GivePoints method in this example.

 int currentPoints = GivePoints(1); 

means currentPoints gets a value of 1.

What this means is that GivePoints is rated. GivePoints based on what the method returns. GivePoints returns the input, so GivePoints will evaluate to 1 in the example above.

+3
source

In your example, the function returns the exact number that you send to it. In this case, any value that you pass as amount . So returning to your current code is a little pointless.

So in your example:

 int x = GivePoints(1000); 

x will be equal to 1000

0
source

just an assumption for your original purpose

 public int GivePoints(int amount) { Points -= amount; return Points; } 

so return will return the updated value of Points

If this is not your code, the code should be

 public void GivePoints(int amount) { Points -= amount; } 
0
source

Return will always exit (leave) the function, nothing will be executed after the return.

Return example:

 public int GivePoints(int amount) { Points -= amount; return; //this means exit the function now. } 

Return an example variable:

 public int GivePoints(int amount) { Points -= amount; return amount; //this means exit the function and take along 'amount' } 

Return an example variable and catch the return variable:

 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) 
0
source

All Articles