More on Compiling C# Files
So far, you have seen how to compile console
applications using csc.exe, but what
about other types of applications? What if you want to reference a
class library? The full set of compilation options for the C#
compiler is of course detailed in the MSDN documentation, but we
list here the most important options.
To answer the first question, you can specify what
type of file you want to create using the /target switch, often abbreviated to /t. This can be one of those shown in the following
table.
If you want a nonexecutable file (such as a DLL) to
be loadable by the .NET runtime, you must compile it as a library.
If you compile a C# file as a module, no assembly will be created.
Although modules cannot be loaded by the runtime, they can be
compiled into another manifest using the /addmodule switch.
Another option we need to mention is /out. This allows you to specify the name of the
output file produced by the compiler. If the /out option isn’t specified, the compiler will base
the name of the output file on the name of the input C# file,
adding an extension according to the target type (for example,
exe for a Windows or console application
or dll for a class library). Note that
the /out and /t, or /target, options
must precede the name of the file you want to compile.
If you want to reference types in assemblies that
aren’t referenced by default, you can use the /reference or /r switch,
together with the path and file name of the assembly. The following
example demonstrates how you can compile a class library and then
reference that library in another assembly. It consists of two
files:
The first file is called MathLibrary.cs and contains the code for your DLL.
To keep things simple, it contains just one (public) class,
MathLib, with a single method that adds
two ints:
You can compile this C# file into a .NET DLL using
the following command:
The console application, MathClient.cs, will simply instantiate this object
and call its Add() method, displaying
the result in the console window:
You can compile this code using the /r switch to point at or reference the newly
compiled DLL:
You can then run it as normal just by entering
MathClient at the command prompt. This
displays the number 15 - the result of
your addition.