Reputation: 21
I was wondering if there was a way to go back to the first line of code from a console application from any point within program. Like a restart function, as in like closing and reopening the console. I'm very new to this so 'obvious' things may not be so obvious to me. can anyone help me please?
Upvotes: 2
Views: 1065
Reputation: 1893
For this case you normally use a while(true)
loop that contains your program.
To restart your programm use the keyword continue
. To end the programm you can use break
Upvotes: 0
Reputation: 20760
You can wrap your entire application into a loop, like so:
public static void Main(string[] args)
{
while (true) {
// your application code
}
}
To jump back to the beginning, invoke
continue;
Note that this will jump "back" to the beginning of the loop, but it will not precisely reset the program - any values that you have stored in variables with a wider scope than the loop will still be there when you are "back" at the beginning of the loop. In fact, you don't go "back" (hence the scare-quotes), continue
just skips the rest of the loop and enters the next iteration of the loop.
To leave the loop (and thereby terminate the application), invoke
return;
(More concretely, this will leave the current method, i.e. Main
.
Upvotes: 2
Reputation: 25
If you want a "restart" try this:
var info = Console.ReadKey();
if (info.Key == ConsoleKey.R)
{
var fileName = Assembly.GetExecutingAssembly().Location;
System.Diagnostics.Process.Start(fileName);
}
But I suggest you to just call a "first method" anyways.
Upvotes: 1