Search code examples
c#methods

why doesn’t MyMethod return a value even though it uses Console.WriteLine()


I was studying C# on w3schools when i saw this code. My question is: MyMethod shouldn't return a value, since there is a "Console.WriteLine()" and a default parameter at the method?

And why Main method return those 3 calls normally, (There's nothing wrong with the code, i just want to understand why)

static void MyMethod(string country = "Norway")
{
  Console.WriteLine(country);
}


static void Main(string[] args)
{
  MyMethod("Sweden");
  MyMethod("India");
  MyMethod();
  MyMethod("USA");
}

Output:

// Sweden
// India
// Norway
// USA

What i expected:

// Norway (from the first method)
// Sweden
// India
// Norway
// USA

Solution

  • MyMethod shouldn't return a value, since there is a "Console.WriteLine()" and a default parameter at the method?

    No. It's because its return type is void.

    Your expectation deviates from your observation because of a misconception.

    The Main method is the "Entry Point" to your Program. It will be called when you execute your program (or hit "Run" in the IDE).

    The MyMethod is a method that is not "automatically" called. It will only be executed if something (i.e. your code) calls it. And finally everything that can call it will somehow be traceable back to the Main method. Admittedly, that's a little bit under-complex, but to understand why you observe what you observe, it should be enough.

    So, when your program is started it will jump to Main, then execute those 4 calls to MyMethod and exit.


    EDIT: As Marc lays down in his answer (rightfully), there are top-level statements now. But for one, I think for beginners, that must be pretty confusing, so for starters, I'd go with the "traditional" Main. Their existence could have led to impression that you should expect what you described in your question, I guess.


    One last thing

    static void MyMethod(string country = "Norway")
        // ^^^^ this is the return type
    

    If a method has a return type of void it doesn't return a value. In your case, you have output (which is different) because that's what Console.WriteLine does.

    If it had anything other than void, let's say string, that would mean it returns a value of that type.

    It would look like this (example)

    static string MyMethod(string country = "Norway")
    {
        return $"Country: {country}"; // << Note the "return" statement!
    }
    

    Usually, you'd want to use the returned value somehow in the calling code. Example:

    // Assume this code is in the Main method
    var countryString = MyMethod("Sweden");
    Console.WriteLine(countryString);