C# Program to Demonstrate the Use of Exit() Method of Environment Class
Environment Class provides information about the current platform and manipulates, the current platform. The Environment class is useful for getting and setting various operating system-related information. We can use it in such a way that retrieves command-line arguments information, exit codes information, environment variable settings information, contents of the call stack information, and time since the last system boot in milliseconds information. By just using some predefined methods we can get the information of the operating system using the Environment class and the Exit() method is one of them. It is used to terminate the current process of the program and return the exit code to the operating system. Calling Exit() method works differently from return statement in the following ways:
- This method always terminates an application whereas a return statement may terminate an application only when it is used in the entry point. of the application like in the main method.
- This method terminates a code immediately, even if other threads are running. Whereas the return statement is called in the entry point of the application and only terminates the application when all the foreground threads are terminated.
- This method requires the caller to have permission to call unmanaged code. Whereas the return statement does not.
- When this method is called from a try or catch block, then the code in any finally block does not execute. whereas a return statement is used called from a try or catch block, the code in the finally block does execute.
- If the Exit method is called when code in a constrained execution region (CER) is running, then the CER will not execute completely. Whereas the return statement is used then CER executes completely.
Where exitCode is a parameter of integer type. It represents the exit code that will return to the operating system. When the value of this parameter is zero then it means that the process is completed. And when the value of this parameter is non-zero then it means then the process is not completed successfully or we can say that zero value represents the error.
Exception: It will throw only SecurityException when a security error is detected.
Code before Exit() function
Code Before Exit() function will work Sum: 20 Subtract: -2