The question is answered, right answer was accepted
Return in c#
Hi, so I have watched videos and read posts about return in c# but I still just don't understand what it does. If you guys could help explain it to me that would be great, thanks!
sounds like you might be skipping a step. $$anonymous$$ake sure you understand "functions" and "expressions" first, then revisit "return".
Answer by Cynikal · Jul 20, 2018 at 12:58 AM
So, return in C#... It returns a value, or it gets out of a function.
So, return on a value, for example:
int MyCustomINTFunction()
{
return 10;
}
int MyValue = 0;
MyValue = MyCustomINTFunction(); //Would return 10.
now, return in a regular function will just 'exit' that function,
so like:
void MyComplicatedCode()
{
if (this != that) return;
SuperRandomLongComplicatedCodeHereThatTakesUpAlotOrAlittleProcessingPower;
}
In that example, if this does not equal that, then we don't actually need to run the rest of the code, so we can 'return' or get OUT of that function. Once return is called, it will exit the code, therefore the 'SuperRandomLong...blah blah' would not actually get called.
Oh ok, so if I say something like
void RandomCode(){
if (Health == something){return}
RandomCode } If the health did == the something, the randomcode would not get called? And if it didn't, the randomcode would get called?
Yes, it's called an early exit.
An early exit helps to keep the code more readable when you have many nested conditions which otherwise would cause many levels of indention. An early exit makes only sense if the whole method can not continue without a certain condition.
For example:
void Some$$anonymous$$ethod(GameObject aGO)
{
if (aGO == null)
return;
Camera cam = Camera.main;
if (cam == null)
return;
$$anonymous$$yComponent comp = aGO.GetComponent<$$anonymous$$yComponent>();
if (comp == null)
return;
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (!Physics.Raycast(ray, out hit))
return;
comp.Shoot(hit.gameObject);
}
The same could be done with nested if statements like this:
void Some$$anonymous$$ethod(GameObject aGO)
{
if (aGO != null)
{
Camera cam = Camera.main;
if (cam != null)
{
$$anonymous$$yComponent comp = aGO.GetComponent<$$anonymous$$yComponent>();
if (comp != null)
{
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
comp.Shoot(hit.gameObject);
}
}
}
}
In the first example it's much clearer what happens next. Since at every early exit the method will return we can easily read downwards. Having more complex conditions and intermediate steps the nested if statements can get very confusing and it's easy to miss something.