Rowan Tarshis Rowan Tarshis - 3 months ago 20
C# Question

Alternative to goto statement

I'm pretty new to C# (started learning it a week ago) with a little bit of experience in batch and Expression 2, and I've been working on a text-based game in an attempt to learn more. I used goto statements at first, but according to pretty much everyone I've found, goto statements are some amalgam of death and despair, so I want to learn cleaner, less evil ways to achieve the same effect. Here's a crummy example script I made to demonstrate what I mean:

using System;

namespace TestScript
{
class Program
{
public static void Main(string[] args)
{
string ConsoleReadinator;
string ConsoleReadinator2;
int Go = 0;

mainmenu:
do
{
Go = 0;
Console.Clear();
Console.WriteLine("Main Menu:");
Console.WriteLine("Store or something");
ConsoleReadinator = Console.ReadLine().ToUpper();
if (ConsoleReadinator == "STORE") { Go = 1; }
} while (Go == 0);

// In-game store example

{
Go = 0;
do
{
Console.Clear();
Console.WriteLine("In-game store I guess");
Console.WriteLine("Stuff you can buy, etc");
ConsoleReadinator2 = Console.ReadLine().ToUpper();
if (ConsoleReadinator2 == "GO") { Go = 1; }
} while (Go == 0);
goto mainmenu;
}
}
}
}


This script is functional, but I'd like to avoid using
goto
as a way to go back to previous statements in order to navigate menus and maybe to repeat algorithms for turn-based games. I read about using methods for this in Alternative to using goto statement in C# (which is basically the same question I have, except a bit more vague), but the example Greg made there didn't work for me at all, to the point that it's probably not worth trying to make that particular example work.

Answer

As far as I can see you want an infinite loop:

  ...
  while (true) 
  {
      do
      {
         ...
      } while (Go == 0);

      Go = 0;

      do
      {
         ...
      } while (Go == 0);
  }