Click here to Skip to main content
15,301,841 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
For example, in C #, I want the automatic program to be closed in the application console environment with the correctness of the condition, and if the condition is not met, the program will continue until the end of the program is closed by pressing the key
int i = int.Parse(Console.ReadLine());
if(i>10)
Console.WriteLine("num not ok ");
//I want to close the program here
else
.
.
.
.
Console.ReadKey();

What I have tried:

Exit();
Close();
I did all the possible ways to do this but unfortunately I could not get the result and tried different methods
Posted
Updated 14-Jan-22 2:55am
v2

It really depends on where that code is: if it's part of your Main method, then teh simplest solution is just
C#
if(i > 10)
   {
   Console.WriteLine("num not ok ");
   return -1;
   }
else
The return statement exits the current method immediately, and in the case of the Main method, that also ends the program - the integer that you return is passed to the system as a "reason for exit" where zero is "normal exit" and any nonm-zero value is an error code.

If you aren't in the Main function, then you need to use
C#
Environment.Exit(-1);
instead of return
   
Use the following code.
Environment.Exit(0);
0 is Exit code, Read more related to ExitCode 
https://docs.microsoft.com/en-us/dotnet/api/system.environment.exitcode
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900