Understanding returned values ​​in C #

So, this question follows from a previous post, which I’m just trying to understand completely before moving on to more complex C # materials.

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 keyword "void" in the first line of code means that the result of the function code does NOT return a value.

What I'm trying to understand is the function calculates the result. It distributes the text (for example: β€œyou win!”, Etc.) based on the result. Is the result of the function an unread value?

With my own (novelty) logic, I would think of one of two things:

  • The return value of this function is a string because it is the result of a computed result.
  • int, int.

, . , . - , , .

+4
3

: # , .

. , , return. , ( ) .

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
+5

A void , , , . :

var myResult = DisplayResult(3, 7)

, myResult .

. " " , .

, , int, .

. , , return:

return "All done!";

, return, .

+4

Console.writeline / DisplayResult

, . / void

:

you can get rid of Console.WriteLine and .ReadLine and replace it with return "result of if statment";, and then call your method / function, for example Console.WriteLine(DisplayResult(/*params*/));, which means that you only write Console.WriteLine()/.ReadLine()once

public static string DisplayResult(int PlayerTotal, int DealerTotal){
    if (PlayerTotal > DealerTotal) {
        return "You Win!"
    } 

    else if (DealerTotal > PlayerTotal) {
        return "Dealer Wins!";

    } else {
        return "It is a Draw!"         }}

in main():

Console.WriteLine(DisplayResult(playerscore,dealerscore));
Console.ReadLine();
0
source

Source: https://habr.com/ru/post/1532763/


All Articles