C
C#10mo ago
Emelie

✅ Newbie question - what exactly does return do?

If I have this piece of code... what exactly happens when the return statement is reached? I understand it exits the current function, but then what is the state of the programme?
6 Replies
Thinker
Thinker10mo ago
In this case, it just exits the method (or function, same thing) and returns back to the place you called the method at.
MODiX
MODiX10mo ago
Thinker
REPL Result: Success
Console.WriteLine("Hi!");
Print();
Console.WriteLine("Goodbye!");

void Print()
{
Console.WriteLine("How are you?");
return;
}
Console.WriteLine("Hi!");
Print();
Console.WriteLine("Goodbye!");

void Print()
{
Console.WriteLine("How are you?");
return;
}
Console Output
Hi!
How are you?
Goodbye!
Hi!
How are you?
Goodbye!
Compile: 599.862ms | Execution: 75.520ms | React with ❌ to remove this embed.
Thinker
Thinker10mo ago
Here you can see how, once the return; is reached, execution goes back to where the method was called. However return also has a second (arguably more important) usage: in your case the method NameInputExists() returns void - which essentially means that the method only does things like writing to the console or similar - but if you were to change that to int for example, now the method would have a return value. Take this method for example
int Add(int a, int b)
{
return a + b;
}
int Add(int a, int b)
{
return a + b;
}
This is a method called Add which has a couple of properties: it takes two parameters - a and b, both of which are integers -, it returns int which means that it should "give back" an integer to the caller, and the value it returns is the result of a + b. So you might use this method like this:
int x = 1;
int y = 5;
// Call the method with x and y as arguments.
int z = Add(x, y);
// z now contains the return value of Add, i.e. a + b.
// We can print this value and show that it is, in fact, 6.
Console.WriteLine(z);
int x = 1;
int y = 5;
// Call the method with x and y as arguments.
int z = Add(x, y);
// z now contains the return value of Add, i.e. a + b.
// We can print this value and show that it is, in fact, 6.
Console.WriteLine(z);
I hope that somewhat made sense
Emelie
Emelie10mo ago
great. Many thanks!!
Denis
Denis10mo ago
$close
MODiX
MODiX10mo ago
Use the /close command to mark a forum thread as answered