The source code to terminate the current running program is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# Program to terminate the current running program.
using System;
class Demo
{
public static void Main()
{
int num = 0;
try
{
Console.Write("Enter the value of num: ");
num = int.Parse(Console.ReadLine());
if (num > 5)
{
Console.WriteLine("Program terminated explicitly");
Environment.Exit(0);
}
}
finally
{
Console.WriteLine("Finally block executed");
}
}
}
Output:
Enter the value of num: 7
Program terminated explicitly
Press any key to continue . . .
Explanation:
In the above program, we created a Demo class that contains the Main() method. In the Main() method we read the value of variable num and then check the value of num. If the value of num is greater than 5 then we print the message "Program terminated explicitly" and terminated the program using the Exit() method of Environment class. If the value of variable num is less than or equal to 5 then the "Finally block executed" message will be printed on the console screen.
Program:
The source code to terminate the current running program is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
Output:
Explanation:
In the above program, we created a Demo class that contains the Main() method. In the Main() method we read the value of variable num and then check the value of num. If the value of num is greater than 5 then we print the message "Program terminated explicitly" and terminated the program using the Exit() method of Environment class. If the value of variable num is less than or equal to 5 then the "Finally block executed" message will be printed on the console screen.