Subscribe

RSS Feed (xml)

Create and Use a Code Library in C#

You were to extend the functionality of the ConsoleUtils class, it could contain functionality useful to many applications. Instead of including the source code for ConsoleUtils in every application, you can build it into a library and deploy it independently, making the functionality accessible to many applications.
To build the ConsoleUtils.cs file into a library, use the command csc /target:library ConsoleUtils.cs. This will produce a library file named ConsoleUtils.dll. To build a library from multiple source files, list the name of each file at the end of the command. You can also specify the name of the library using the /out compiler switch; otherwise, the library is named after the first source file listed. For example, to build a library named MyFirstLibrary.dll from two source files named ConsoleUtils.cs and WindowsUtils.cs, use the command csc /out:MyFirstLibrary.dll /target:library ConsoleUtils.cs WindowsUtils.cs.
Before distributing your library, you might consider strong naming it so that nobody can modify your assembly and pass it off as being the original. Strong naming your library also allows people to install it into the global assembly cache, which makes reuse much easier. (Recipe 1.9 describes how to strong name your assembly and recipe 1.14 describes how to install a strong-named assembly into the global assembly cache.) You might also consider signing your library with an Authenticode signature, which allows users to confirm that you are the publisher of the assembly—see recipe 1.12 for details on signing assemblies with Authenticode.
To compile an assembly that relies on types declared within external libraries, you must tell the compiler which libraries are referenced using the /reference compiler switch. For example, to compile the HelloWorld.cs source file (from recipe 1.1) if the ConsoleUtils class is contained in the ConsoleUtils.dll library, use the command csc /reference:ConsoleUtils.dll HelloWorld.cs. Three points worth remembering are
  • If you reference more than one library, separate each library name with a comma or semicolon, but no spaces. For example, /reference:ConsoleUtils.dll,WindowsUtils.dll.
  • If the libraries aren't in the same directory as the source code, use the /lib switch on the compiler to specify the additional directories where the compiler should look for libraries. For example, /lib:c:\CommonLibraries,c:\Dev\ThirdPartyLibs.
  • If the library you need to reference is a multi-file assembly, reference the file that contains the assembly manifest. (For information about multi-file assemblies, see recipe 1.3.)

No comments:

Post a Comment

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail