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 I target switch, often abbreviated to It. This can be one of those shown in the following table.
If you want a non-executable 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 I add module switch.
Another option we need to mention islout. 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 lout 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 Preference or Ir 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 class library
- A console application, which will call a class in the library.
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:
csc /t:library MathLibrary.cs
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 Ir switch to point at or reference the newly compiled DLL:
csc MathClient.cs /r.MathLibrary.dll
You can then run it as normal just by entering Math Client at the command prompt. This displays the number 15 – the result of your addition.