Search code examples
c#loopsprogram-entry-point

C# Method that restarts Main()


I have a C# method, if a condition is not met I want to re-run the Main() method. There are a few posts saying use loops to do this. GoTo would also work - but don't use it. Or restart the application.

No one has given a clear newbie-level explanation about the loops.

C# example:

public static void Method3(int userChoice){
 if(userChoice == 1){
  Console.WriteLine("do this");
 }
 else{
  Main(); // How to run the main program again from the start ?
 }
}

public static void Main(string[] args)
{
 Method1();
 int userChoice = Method2();
 Method3(userChoice);  // I want Method3 to go back to Method1() if the else statement is met.
}      

In python this is real easy - you just call Main() from the function.


Solution

  • You can have Method3() return a bool so the Main() method knows whether to try again.

    public static bool Method3(int userChoice)
    {
        if (userChoice == 1)
        {
            Console.WriteLine("do this");
            return false;
        }
    
        return true;
    }
    
    public static void Main(string[] args)
    {
        bool tryAgain;
        do
        {
            Method1();
            int userChoice = Method2();
            tryAgain = Method3(userChoice);
        } while (tryAgain);       
    }
    

    Simply calling Main() again instead of looping is another approach, but has some disadvantages.

    • You'll have to come up with the args argument somehow. Maybe it's just an empty array in your case.
    • It's a recursive call and affects the stack trace. After so many recursive calls, your application will crash.
    • It decreases maintainability. You'll have to remember in the future if you want to add anything to the top of the Main() method that you're calling it from somewhere. It lends itself to the introduction of potentially hard-to-diagnose bugs. Using the loop approach encapsulates the behavior. From just looking at Main(), it's obvious that Method3() might cause another loop.