A library can be made of a single file or as many
files as necessary. A file that is part of a library can contain one or
more classes. Each class should implement a behavior that can eventually be
useful and accessible to other classes. The classes in a library are
created exactly like those we have used so far. Everything depends on how
you compile it. To create a library, start by typing
its code in a text file. Once the library is ready, to compile it, at the
Command Prompt, you would type csc /target:library NameOfFile.cs
and press Enter. After doing this, a library with the name
of the file and the extension .dll would be created. If you want a custom name,
use the following syntax: csc /target:library /out:DesiredNameOfLibrary.dll NameOfFile.cs
Practical
Learning: Creating a Library |
|
- To start a new project, on the main menu, click File -> New Project...
- In the New Project dialog box, click Class Library
- Set the Name to Operations1 and click OK
- Change the file as follows:
using System;
namespace Operations1
{
public class Operations
{
public static double Addition(double x, double y)
{
return x + y;
}
public static double Subtraction(double x, double y)
{
return x - y;
}
public static double Multiplication(double x, double y)
{
return x * y;
}
public static double Division(double x, double y)
{
if (y == 0)
return 0;
return x / y;
}
}
}
|
- In the Solution Explorer, right-click Class1.cs and click Rename
- Change the name to Operations.cs and press Enter
- To save the project, on the Standard toolbar, click the Save All button
- Click Save to save everything
- On the main menu, click Project -> Operations1 Properties
- In the Output Type combo box, make sure Class Library is selected:
- Click the X button to close the Properties window
- To create the library, on the main menu, click Build -> Build Solution
- To start another project, on the main menu, click File -> New
Project...
- In the New Project dialog box, select Console Application
- Set the Name to Algebra1 and press Enter
- In the Solution Explorer, right-click References and click Add
Reference...
- Click the Browse tab
- In the list of folders, double-click Operations1 and locate the
Operations1.dll file (it should be in the Release (or the Debug) sub-folder
of the bin folder)
- Click Operations1.dll
- Click OK.
In the Solution Explorer, expand the References node if necessary and make
sure that there is a new node labeled Operations1
- Access the Program.cs file and change it as follows:
using System;
namespace Algebra1
{
class Program
{
static int Main()
{
double Number1 = 244.58;
double Number2 = 5082.88;
double Result =
Operations1.Operations.Addition(Number1, Number2);
Console.WriteLine("{0} + {1} = {2}\n",
Number1, Number2, Result);
return 0;
}
}
}
|
- Execute the application to test it. This would produce:
244.58 + 5082.88 = 5327.46
Press any key to continue . . .
|
- Close the DOS window
|
|