F.4 Creating DLL assemblies using csc.exe


F.4 Creating DLL assemblies using csc.exe

If you are using csc.exe , you will need to know how to reference classes coded in other assemblies using the /reference option.

Let's say you have two classes, called MyClass1 and MyClass2 , in separate source files. [4] MyClass1 creates a new instance of MyClass2 in its Main method.

[4] Of course, you can put them into the same source file and no referring will be required. But I am trying to show how you can reference something coded in another source file (which will eventually be compiled into a separate assembly).

 1: // MyClass1.cs 2: public class MyClass1{ 3:   public static void Main(){ 4:     MyClass2 mc2 = new MyClass2(); 5:     System.Console.WriteLine(mc2.Add(3,4)); 6:   } 7: } 
 1: // MyClass2.cs  in separate source file 2: public class MyClass2{ 3:   public int Add (int a, int b){ 4:     return a + b; 5:   } 6: } 

You need to compile MyClass2.cs into a DLL assembly. It cannot be an EXE assembly since it doesn't contain a Main method, and hence isn't 'executable'.

Use the /target:library [5] option to compile MyClass2.cs into MyClass2.dll :

[5] You can use /t instead of /target . /t is a shortcut.

 c:\expt>csc  /target:library  MyClass2.cs 

When you compile MyClass1.cs , make sure you reference MyClass2.dll like this:

 c:\expt>csc  /reference  :MyClass2.dll MyClass1.cs 

Try compiling without the /reference:MyClass2.dll switch and the compiler will complain that MyClass2 is an unknown symbol.

You can reference multiple DLLs when compiling a single C# source file by separating them with commas:

 /reference:MyClass2.dll,MyClass3.dll,MyClass4.dll. 

You can also combine multiple source files into a single DLL assembly. The following command will compile both source files and put the resultant IL codes into a single DLL assembly called MyClass2.dll :

 c:\expt>csc /target:library MyClass2.cs MyClass3.cs 


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