So this question follows on from a previous post that I am just trying to understand in full before I move on to more complicated C# stuff.
My question relates specifically to the return value of a function.
Consider the following function code:
public static void DisplayResult(int PlayerTotal, int DealerTotal){
if (PlayerTotal > DealerTotal) {
Console.WriteLine ("You Win!");
Console.ReadLine ();
}
else if (DealerTotal > PlayerTotal) {
Console.WriteLine ("Dealer Wins!");
Console.ReadLine ();
} else {
Console.WriteLine ("It is a Draw!");
Console.ReadLine ();
}
I could be wrong of course but I believe that the "void" keyword in the first line of code means that the function code result does NOT return a value.
What I am trying to understand is - the function calculates a result. It distributes text (eg: "you win!" etc) based on the result. Is the result of the function not considered a value?
By my own (novice) logic, I would have thought one of two things:
I hope this makes sense. I think understanding this concept will make it easier for me in future to write functions without second guessing return values. If anyone has an example of a function that actually DOES return a value it would also be appreciated.
A bit of terminology first: C# doesn't have functions, it has methods.
Return values give some value to the method's caller. They aren't related to the statements executed within that method, except for the return
statement. The method's signature dictates what (if any) type is returned by that method.
public void NoReturnValue()
{
// It doesn't matter what happens in here; the caller won't get a return value!
}
public int IntReturnValue()
{
// Tons of code here, or none; it doesn't matter
return 0;
}
...
NoReturnValue(); // Can't use the return value because there is none!
int i = IntReturnValue(); // The method says it returns int, so the compiler likes this
A void
method, as you have surmised, is one that returns no value. If you wrote:
var myResult = DisplayResult(3, 7)
you would get an error because there is no returned value to assign to myResult
.
Your method outputs text to the console. This is a "side effect" of the method, but has nothing to do with its return value.
Also, the fact that your method interacts with int
s has nothing to do with what its return value is either.
As a final point. The most basic thing to keep in mind is that a return value is a value that comes after the return
keyword:
return "All done!";
Anything that doesn't involve the return
keyword is not a return value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With