can someone give me an example of what “return” does and how to use it?
can someone give me an example of what “return” does and how to use it?
34 Replies
what have you searched for about it?
It returns a value from a method
I searched Google and they say that it returns a value but I can’t find examples
Jump statements - break, continue, return, and goto - C#
C# jump statements (break, continue, return, and goto) unconditionally transfer control from the current location to a different statement.
the first link i see is the one daniel linked
adding c# to the end
that page has an example
Console.WriteLine("First call:");
DisplayIfNecessary(6);
Console.WriteLine("Second call:");
DisplayIfNecessary(5);
void DisplayIfNecessary(int number)
{
if (number % 2 == 0)
{
return;
}
Console.WriteLine(number);
}
Angius
REPL Result: Success
Console Output
Compile: 357.789ms | Execution: 27.621ms | React with ❌ to remove this embed.
What is it returning?
Oh
what do you think it's returning?
oh, you picked the one that doesn't return anything
you should read the entire section
Ah, in this case, nothing. The method is
void
the section has 2 examples, one that doesn't return anything and one that does
return
also stops the method from executing furtherAnd void means u aren’t returning anything
Right?
right
In this example how could it return number1 and number2 when they aren’t numbers
they are numbers
look at the data types
number1 + number2
is an expression that adds the numbers stored in number1
and number2
and gives you a new numberSo 56 and 887
so the return statement returns the result of that expression
no
they can be any number
Ik but in this example
in this example they happen to be set to those
Yeah
So the public static sets 56 and 887 as number1 and number2
no
public
and static
are modifiers applied to the method definitionIk I meant like the method in general
My bad
no, the method doesn't set anything
it accepts values passed to it when called like
Add(56, 887);
the method itself doesn't have anything to do with which values it getsLast question on return
Console.WriteLine("First call:");
DisplayIfNecessary(6);
Console.WriteLine("Second call:");
DisplayIfNecessary(5);
void DisplayIfNecessary(int number)
{
if (number % 2 == 0)
{
return;
}
Console.WriteLine(number);
}
If we wrote DisplayIfNecessary(5)
Number would equal to 5?
Yes
And number would only equal 5 if we put “return DisplayIfNecessary(5);” Correct?
No, why?
Just calling the method and passing a value into the parameter makes the parameter take the value
Especially since
DisplayIfNecessary()
is a void
method too, you cannot return a result of a void
methodOh, so the return, by itself, does it. Okay.
The return has nothing to do with the parameters. A method can be
void
and have no return, and you can still give it parametersOkay 👍
if it helps, parameters/arguments are what go into the method and the return is what comes out