Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does a return statement do in C#? [closed]

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?

like image 685
Mikey D Avatar asked Mar 06 '13 02:03

Mikey D


2 Answers

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.

like image 183
chris-mv Avatar answered Sep 22 '22 02:09

chris-mv


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)
like image 32
Morris S Avatar answered Sep 18 '22 02:09

Morris S