Storing Multiple Modules in an Assembly

Assemblies can contain several modules, and we're going to create a multi-module assembly next . An assembly includes a hash code for each module, which is a numeric representation of the module's code used for version verification. The Visual Studio IDE can't create multi-module assemblies for C#, although it can for C++, so we're going to use the command-line compiler, csc, in this example.

This example shows how to link several modules into the same assembly. In this case, we're going to define a string-handling class, ch13_02, in one module, and use it in another. In ch13_02.cs, we'll define the ch13_02 class in a namespace called MultiModule and give that class a property named Text that will hold a string of text:

Listing 13.4 Defines the ch13_03 Assembly (ch13_04.cs)

To compile the first module, ch13_02.cs, use the /t:module switch like this:

C:\>csc /t:module ch13_02.cs

This creates the file ch13_02.netmodule. The code in ch13_03.cs makes use of the ch13_02 class defined in ch13_02.netmodule, so we'll use the /addmodule switch to include the needed code from ch13_02 when we compile ch13_03:

C:\>csc /addmodule:ch13_02.netmodule /t:module ch13_03.cs

This creates ch13_03.netmodule. All we need is the final module, created from ch13_04.cs, which holds the manifest information for this assembly:

C:\>csc /t:module ch13_04.cs

This creates ch13_04.netmodule. To link these modules into one assembly, which we'll call ch13_03.exe (because Main is in ch13_03.cs), you use the assembly linker, al, which comes with Visual Studio, al.exe (where xxxxxxxxxx is the .NET version number). Here's how we create our assembly. Note the /main switch, which lets you specify the entry point for the assembly, the /out switch, which lets you name the output file, and the /t:exe switch, which specifies that the type of this assembly is an .EXE file: