Trying to learn how to use return variables, is this a good practice exercise?
class Program
{
static int MyMethod(int x, int y)
{
int xy = x + y;
return xy;
}
public static void Main(string[] args)
{
int answer = MyMethod(3, 4);
Console.WriteLine(answer);
}
}
6 Replies
Well, it does make use of the
return
So... sureAlthough I personally wouldn't suggest to make methods like Add without it being special.
also way shorter to just write
3 + 4
instead of Add(3, 4)
they only used that because theyre trying to learn how to use return
all you need is
return
with the correct type that is required for the method
if its void
, then just return
with no variable
what you did is correct, but logically not best practice (for the reason to make a method that just does addition)
something a little more complex, but might help with visualizing how return works:
i try to keep my methods short.
but when i have the need for a result, i call that variable 'result'
in fact when i start writing a method it became a standard pattern to write this
and then just add modifications to result between the initialization and the return
this way you will have a valid result no matter what
in fact it also helps when adding strange if else blocks that are sometimes making the methods harder to understand
so instead of
you can write
ps: i know these are simple cases and especially the first one can be written soooo much shorter. these are just meant to be an example
That said, there's a case to be made for Fail Fast, which I personally subscribe to
Seems like multiple very hardened responses to a beginner-question 😁