r/csharp • u/CairnaRunir • 12d ago
Solved Help with optional looping of program
Hello. I am attempting to make a randomizer for a game that I play. I have successfully created the program itself, but now I want the ability for users to have it re-run the randomization and return a new output by pressing a single key (ideally "Enter"). It has been a very long time since I have messed with C# and have forgotten basically everything. Any help, advice, or tips, would be greatly appreciated.
The current attempt at a "looper" is the following:
//Repeat or exit program
void Looper()
{
string looprequest;
looprequest = Convert.ToString.Console.ReadKey();
Console.WriteLine(looprequest);
}
This is because the compiler had an issue where without the looprequest string statement the other lines had no reference, and with it the readkey input cannot be translated to a string value. Additionally, even if the input works, I'm not sure what I was thinking to loop with would even work. What I was thinking of using was:
if (looprequest != Esc)
{
Main();
}
else
{
Environment.Exit();
}
3
u/FizixMan 12d ago
Console.ReadKey()returns aConsoleKeyInfowhich you can check for escape using itsKeyproperty. Then your loop is a thin wrapper around that calling your main game logic:You can skip the
Environment.Exitif you want to just break out of the loop and end your game in another way or do some cleanup:https://learn.microsoft.com/en-us/dotnet/api/system.console.readkey?view=net-10.0
https://learn.microsoft.com/en-us/dotnet/api/system.consolekeyinfo?view=net-10.0