Search code examples
c#methodsconsole-applicationcallaccess-modifiers

How are Methods with different modifiers called exactly


this is my first post. I am trying to run this C# code I am getting an undesired output:

When I run the following code:

class Car1
    {
        public void PublicHelperMethod()
        {
            Console.WriteLine("Inside Public helper method");
            Console.WriteLine("Calling Private Helper method.." + PrivateHelperMethod());
        }

        private string PrivateHelperMethod()
        {
            Console.WriteLine("Private Helper Method Called!");
            return "Now Inside Private Helper method";
        }
    }

I am expecting the output to be in this order:

Inside Public helper method

Calling Private Helper method..Private Helper Method Called!

Now Inside Private Helper method

But I am getting the following output:

Inside Public helper method

Private Helper Method Called!

Calling Private Helper method..Now Inside Private Helper method

What am I missing? Why did the order change? Thanks in advance.


Solution

  • This is all because of the way in which C# evaluates expressions.

    Let's do this method call by method call.

    Console.WriteLine("Inside Public helper method");
    

    Nice and easy, prints Inside Public helper method.

    Console.WriteLine("Calling Private Helper method.." + PrivateHelperMethod());
    

    Here, C# sees that you want to print something. But the thing that you want to print is "Calling Private Helper method.." + PrivateHelperMethod(). This means that it must know the return value of PrivateHelperMethod first before printing. To know the return value, the method has to be called. Inside PrivateHelperMethod, we have

    Console.WriteLine("Private Helper Method Called!");
    

    Again, a simple one. Just prints Private Helper Method Called!.

    Then PrivateHelperMethod returns a value. The value is appended to Calling Private Helper method... Now the whole thing that you want to print has been fully evaluated, it prints Calling Private Helper method..Now Inside Private Helper method.

    what do I do to get the desired output without having two Console.WriteLine statements?

    class Car1
    {
        public void PublicHelperMethod()
        {
            Console.WriteLine("Inside Public helper method");
            Console.WriteLine("Calling Private Helper method.." + PrivateHelperMethod());
        }
    
        private string PrivateHelperMethod()
        {
            return "Private Helper Method Called!\nNow Inside Private Helper method";
        }
    }