Help with return

Throughout this section Gary often says that methods “don’t need to return anything”. I should probably know this by now but could anyone explain the concept of returning and not returning to me?

I’ve used return a few times throughout the course but it would be helpful to have a better understanding of what that means and what is happening within the method.

Thanks in advance!

Hi Nob,

Usually, a method in C# is expected to return something. A silly example:

int GetSum (int a, int b)
{
    int sum = a + b;
    return sum;
}

Just by reading this code, do you have an idea of the purpose of this method? If so, let’s call it.

void Start()
{
    int sumA = GetSum(1, 2);
    int sumB = GetSum(99, 1);
    int sumC = GetSum(7, 3);
   
    Debug.Log(sumA);
    Debug.Log(sumB);
    Debug.Log(sumC);

    // return; is optional
}

You could either guess or you could test the code in one of your scripts. Feel free to change the values inside the parentheses of the GetSum method.

If you don’t have time to test the code yourself but if you want to check your guess anyway, this would be the output in the Console:

// 3
// 100
// 10

What’s the difference between the GetSum method and the Start method apart from the things inside the parentheses and the method names? The return type. The GetSum method was declared with int, and the Start method with void.

Unsurprisingly, the GetSum method returns an integer while the Start method does not return anything.

And that’s what Gary means by “returning something/nothing”.

Did this clear it up for you? :slight_smile:


See also:

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms