Freigeben über


Tips for Writing Console Applications

I write a lot of console applications for everything from testing a snippet of .NET code to simple utilities to automate a process or solve a problem. Here are a couple of tips for writing console applications.

Use Exit Codes

Traditionally console applications return an exit code of 0 for success and non-zero for failure. Some applications take this further and do things like return negative numbers for errors and positive numbers for warnings. Be aware that a number of tools (for example, MSBuild) will assume that anything non-zero is a failure. For this reason I typically don’t return a special exit code for warnings, I do however return a unique (usually negative exit code) for each error condition.

Use Enumerations for Exit Codes

You can simplify keeping track of your exit codes by using a private enumeration, this also serves as a way of documenting your exit codes.

class Program

{

    static int Main(string[] args)

    {

        if (args.Length < 1 || args.Length > 3)

        {

            Console.Error.WriteLine("USAGE: ...");

            return (int)ExitCode.InvalidUsage;

        }

        return (int)ExitCode.Success;

    }

    private enum ExitCode

    {

        Success = 0,

        InvalidUsage = -1

    }

}

Simplify Development and Debugging

When running a console application from a debugger it can often be frustrating that the console window closes before you can review the output. The simple solution is to add a Console.ReadLine() to the end of your application’s code but it’s easy to accidentally leave this in there. So why not leave this code in your application permanently:

if (Debugger.IsAttached)

{

    Console.ReadLine();

}