F.6 Referencing an external module during compilation of an assembly


You have seen how to use the /reference:AssemblyName.dll option of csc.exe to reference an assembly. What happens if the method or class you want to use is not in an assembly, but in a module instead? You cannot reference a module which is not in the same assembly, but you can add that module in the new assembly you are generating during compilation.

Here's an example. It will compile MyMath.cs into a module instead of an assembly.

 1: // MyMath.cs 2: public class MyMath{ 3:   public static int Triple(int a){ 4:     return a*3; 5:   } 6: } 

The following command generates MyMath.netmodule :

 c:\expt>csc /target:module MyMath.cs 

Another class, MyClass.cs , invokes the static method in MyMath :

 1: // MyClass.cs 2: public class MyClass{ 3:   public static void Main(){ 4:     System.Console.WriteLine(MyMath.Triple(1)); 5:   } 6: } 

As expected, during a normal compilation, you get a compiler error.

[View full width]
 
[View full width]
c:\expt>csc MyClass.cs MyClass.cs(4,30): error CS0246: The type or namespace name 'MyMath' could not be found graphics/ccc.gif (are you missing a using directive or an assembly reference?)

If you try to use the /reference flag to reference a module, it still doesn't work:

[View full width]
 
[View full width]
c:\expt>csc /reference:MyMath.netmodule MyClass.cs error CS1509: Referenced file 'C:\expt\MyMath.netmodule' is not an assembly; use ' graphics/ccc.gif /addmodule' option instead

Use the /addmodule option to include the module into your class during compilation:

 c:\expt>csc  /addmodule:  MyMath.netmodule MyClass.cs 

Compilation should work, and MyClass.exe runs.

Note that the codes in MyMath.netmodule are not really physically inserted into MyClass.exe but rather referenced as an external resource. If you delete MyMath.netmodule , MyClass.exe will no longer be able to execute.

You can use the /addmodule option together with the /target:library flag to generate a DLL assembly instead of an EXE assembly.



From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net