Exit Console Application in C#

  1. Exit a Console Application With the return Method in C
  2. Exit a Console Application With the Environment.Exit() Method in C

This tutorial will discuss methods to exit a console application in C#.

Exit a Console Application With the return Method in C

If we want to exit our application, we can use the return statement in C#. The return statement ends the execution of a method and returns the control to the calling or the main method. We can use the return statement inside the main() function to end our console application’s execution. The following code example shows us how to exit a console application with the return statement in C#.

using System;

namespace exit_console_application
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("HI");
            return;
            Console.WriteLine("Hello");
        }
    }
}

Output:

HI

We exited the console application with the return statement in C# in the above code. The above code only prints HI because the application execution ends before the line Console.WriteLine("Hello"); gets executed. The only disadvantage of using this method is that we cannot exit the application from any other function.

Exit a Console Application With the Environment.Exit() Method in C

We can also use the Environment.Exit() method to exit a console application in C#. The Environment.Exit() method is used to end the execution of a console application in C#. The Environment.Exit() function returns an exit code to the operating system. See the following example.

using System;

namespace exit_console_application
{
    class Program
    {
        static void func()
        {
            Console.WriteLine("First Statement");
            Environment.Exit(0);
            Console.WriteLine("Second Statement");
        }
        static void Main(string[] args)
        {
            Console.WriteLine("HI");
            func();
        }
    }
}

Output:

HI
First Statement

In the above code, we ended the execution of the application from the func() function with the Environment.Exit() function in C#. The advantage of this method over the previous method is that we can exit the application from any function.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp Console

  • Properly Exit an Application in C#