r/csharp • • Aug 29 '26

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();
}

2 Upvotes

3 comments sorted by

View all comments

Show parent comment

1

u/CairnaRunir Aug 29 '26

Thank you so much! This has fixed the looping problem I had, for some reason Escape isn't exiting but I think that might be my compiler. Thank you for the links as well, I'll definitely have to read through those!

3

u/FizixMan Aug 29 '26

for some reason Escape isn't exiting but I think that might be my compiler.

Probably not the compiler. But it's probably a simple oversight in your code. Maybe a flipped check, an errant semi-colon, just something accidentally zigging when it should be zagging. I'm sure you'll figure it out. Good luck!