Visual C# 2005 Recipes



A P P L I C AT I O N D E V E L O P M E N T
2
1-1. Create a Console Application from the Command
Line

Problem
You need to use the C# command-line compiler to build an application that does not require
a Windows graphical user interface (GUI) but instead displays output to, and reads input from, the
Windows command prompt (console).

Solution
In one of your classes, ensure you implement a static method named Main with one of the following
signatures:

public static void Main();
public static void Main(string[] args);
public static int Main();
public static int Main(string[] args);

Build your application using the C# compiler (csc.exe) by running the following command
(where HelloWorld.cs is the name of your source code file):
csc /target:exe HelloWorld.cs

Note
If you own Visual Studio, you will most often use the Console Application project template to create new
console applications. However, for small applications, it is often just as easy to use the command-line compiler. It
is also useful to know how to build console applications from the command line if you are ever working on a machine
without Visual Studio and want to create a quick utility to automate some task.

How It Works
By default, the C# compiler will build a console application unless you specify otherwise. For this
reason, it's not necessary to specify the /target:exe switch, but doing so makes your intention
clearer, which is useful if you are creating build scripts that will be used by others or will be used
repeatedly over a period of time.

To build a console application consisting of more than one source code file, you must specify
all the source files as arguments to the compiler. For example, the following command builds an
application named MyFirstApp.exe from two source files named HelloWorld.cs and ConsoleUtils.cs:

csc /target:exe /main:HelloWorld /out:MyFirstApp.exe HelloWorld.cs ConsoleUtils.cs
The /out switch allows you to specify the name of the compiled assembly. Otherwise, the
assembly is named after the first source file listed--HelloWorld.cs in the example. If classes in both
the HelloWorld and ConsoleUtils files contain Main methods, the compiler cannot automatically
determine which method represents the correct entry point for the assembly. Therefore, you must
use the compiler's /main switch to identify the name of the class that contains the correct entry point
for your application. When using the /main switch, you must provide the fully qualified class name
(including the namespace); otherwise, you will get a CS1555 compilation error: "Could not find
`HelloWorld' specified for Main method."

If you have a lot of C# code source files to compile, you should use a response file. This simple
text file contains the command-line arguments for csc.exe. When you call csc.exe, you give the name
of this response file as a single parameter prefixed by the @ character. For example: