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

2020-02-12 05:35发布

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?

5条回答
叛逆
2楼-- · 2020-02-12 05:37

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.

查看更多
倾城 Initia
3楼-- · 2020-02-12 05:52

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.

查看更多
相关推荐>>
4楼-- · 2020-02-12 05:56

just a guess for your original goal

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

so return will return the updated value of Points

if this is not your case the code should be

public void GivePoints(int amount)
{
    Points -= amount;
}
查看更多
别忘想泡老子
5楼-- · 2020-02-12 05:58

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)
查看更多
【Aperson】
6楼-- · 2020-02-12 06:01

In you example, the function is returning the exact number you are sending to it. In this case, whatever value you pass as amount. Therefore, the return in your current code is a bit pointless.

So in your example:

int x = GivePoints(1000);

x will equal 1000

查看更多
登录 后发表回答