A library is a program that contains classes and/or
other resources that other programs can use. Such a program is created with
the same approach as the programs we have done so far. Because a library is
not an executable, it does not need the Main() function. A library
usually has the extension .dll (other types of libraries in Microsoft
Windows can have the extension .lib or another extension).
Application:
Introducing Custom Libraries
|
|
- Start Microsoft Visual C#
- To start a new application, on the main menu, click File -> New
Project...
- In the left list, click Windows
- In the right list, click Empty Project
- Change the Name to SaleRecord and click OK
- To save the project, on the Standard toolbar, click the Save All
button
- If you accept the suggest folder (in the Location), make a note of
it. Otherwise, enter a different location and keep it in mind
- Click Save
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 of other programs.
To create a library, on the main menu of Microsoft
Visual Studio, you can click File -> New Project... In the middle list,
you can click Empty Project or click Class Library. Then give it a name:
If you had selected Empty Project in the New Project
dialog box, you should open the Properties window and, in the Output Type
combo box, select Class Library:
In both cases, a skeleton code would be presented to you
and you can complete it as you see fit. Here is an example:
public class Algebra
{
public double Addition(double x = 0, double y = 0)
{
return x + y;
}
public double Subtraction(double x = 0, double y = 0)
{
return x - y;
}
public double Multiplication(double x = 0, double y = 0)
{
return x * y;
}
public double Division(double x = 0, double y = 1)
{
return x / y;
}
}
Application:
Starting a Library
|
|
- On the main menu, click Project -> SaleRecord Properties...
- In the Output Type combo box, select Class Library
- To create a new file, on the main menu, click Project -> Add New
Item...
- In the left list, click Code
- In the right list, click Code File
- Change the Name to StoreItem and click Add
- Change the document as follows:
public class StoreItem
{
public int itemNumber;
public string itemName;
public string size;
public decimal unitPrice;
}
- Save all
Since you would be creating a library and not an
executable, to compile the project:
- On the main menu, you can click Build -> Build ProjectName
- In the Solution Explorer, you can right-click the name of the
project and click Build
- In the Class View, you can right-click the name of the project and
click Build
If you want to compile a library at the Command Prompt,
you would type:
csc /target:library NameOfFile.cs
and press Enter.
Application:
Building a Library
|
|
- To create the library, on the main menu, click Build -> Build
Solution
After building the project, you can use it. You can use
it in the same project where the library was built or you can use it in
another project. If you are working in Microsoft Visual Studio, you can
start by creating a new project. To use the library, you would have to
reference the library. To do this:
- On the main menu, you would click Project -> Add Reference...
- In the Solution Explorer, you would right-click References and click
Add Reference...
In both cases, the Add Reference dialog box would come
up. You can click the Browse tab, locate the folder where the library
resides and select it:
After selecting the library, you can click OK. You can
then use the classes and methods of the library like you would use those of
the .NET Framework. Here is an example:
using System;
public class Exercise
{
static void Main()
{
Algebra alg = new Algebra();
double number1 = 244.58;
double number2 = 5082.88;
double result = alg.Addition(number1, number2);
Console.Write(number1);
Console.Write(" + ");
Console.Write(number2);
Console.Write(" = ");
Console.WriteLine(result);
}
}
If you want to compile the project at the Command
Prompt, you would type something like the following:
csc /target:library /out:DesiredNameOfLibrary.dll NameOfFile.cs
This would produce:
244.58 + 5082.88 = 5327.46
Press any key to continue . . .
Application:
Using a Custom Library
|
|
- To start a new project, on the main menu, click File -> New
Project...
- In the middle list, click Empty Project
- Change the Name to DepartmentStore5 and click Add
- In the Solution Explorer, under DepartmentStore5, right-click
References and click Add Reference...
- Click the Browse tab
- Locate the folder where the library was created
- Select SaleRecord.dll
- Click OK
- In the Solution Explorer, right-click DepartmentStore5 -> Add -> New
Item...
- In the middle list, click Code File
- Change the name to DepartmentStore and click Add
- Change the file as follows:
using System;
public class Program
{
static int Main()
{
StoreItem si = new StoreItem();
si.itemNumber = 660284;
si.itemName = "Tropical Wool Neutral Jacket";
si.unitPrice = 200.00M;
Console.WriteLine("Store Inventory");
Console.Write("Item #: ");
Console.WriteLine(si.itemNumber);
Console.Write("Item Name: ");
Console.WriteLine(si.itemName);
Console.Write("Unit Price: ");
Console.WriteLine(si.unitPrice);
Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
System.Console.ReadKey();
return 0;
}
}
- Execute the application:
Store Inventory
Item #: 660284
Item Name: Tropical Wool Neutral Jacket
Unit Price: 200.00
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Press any key to continue . . .
- Press any key and return to your programming environment
Introduction to Built-In Libraries
|
|
Introduction to the C# Library
|
|
Unlike many other languages such as C++ or (Object)
Pascal (Delphi), C# is known as being one of the languages that don't have
their own library. This is not an anomaly and it doesn't make C# less
efficient than any other language. That's just the way the language was
designed. In fact, you will find out in this and other lessons that C# can
benefit from using the libraries in the other languages, thanks to its
tremendous flexibility.
In reality, C# has a tiny library made of just a few
classes you will almost never use. The library is named
Microsoft.CSharp.dll. In the new C# 4.0 release of the language,
the library was slightly updated and includes a new data type we must now
use.
If you create a console application, Microsoft Visual
Studio automatically adds the Microsoft.CSharp.dll library
to your project. Otherwise, if you create an empty project but you want to
use this library, you can easily add it using the Add Reference dialog box.
In previous lessons, we used different data types (short,
int, float, double,
decimal, and string). We saw that the data
type communicates to the compiler how much memory it should reserve for the
variable. In fact, if you position the mouse on top of a data type in the
Code Editor, a tool tip would let you know how much space its variable would
use:
We also saw that if you don't want to specify a data
type, when declaring the variable, you can use the var
keywork but you must initialize the variable before using it. After
initializing the variable, the compiler reserves memory based on its
estimation from the value you assigned. When using the variable, if you
position the mouse on it, the Code Editor would show the data type that was
assigned to it:
In some scenarios, you would not know how much space is
appropriate, until you need to use the variable. In other words, you would
not worry the compiler with the variable's logistics until the operation
that needs the variable accesses it. Such a variable is referred to as
dynamic.
To declare a dynamic variable, you
use the dynamic keyword. Here is an example of declaring a
dynamic variable:
public class Exercise
{
static int Main()
{
dynamic value;
return 0;
}
}
Unlike a variable declared with the var
keyword, you don't have to initialize a dynamic variable when declaring it.
Still, before using it, at one time or another, you must assign a value to
it. When you assign a value to a dynamic variable, the compiler doesn't
check how much space would suit the variable and if you position your mouse
on the variable, the Code Editor would only tell you that the variable is
dynamic:
A dynamic variable is mostly used if you are creating a
project that would communicate with an extenal application and it would use
values coming from that application. An example is a Microsoft Word document
or a Microsoft Excel spreadsheet developed using the C# language (or from
Microsoft Visual C#) that imports an external library.
Application:
Using a Dynamic Variable
|
|
- To start a new project, on the main menu, click File -> New
Project...
- In the middle list, click Empty Project
- Change the Name to DepartmentStore6 and click Add
- In the Solution Explorer, right-click DepartmentStore6 -> Add -> New
Item...
- In the middle list, click Code File
- Change the name to PayrollProcessing and click Add
- On the main menu, click Project -> Add Reference...
- In the Add Reference dialog box, click the .NET tab
- In the list, click Microsoft.CSharp
- Click OK
- Change the file as follows:
using System;
public class Payroll
{
static int Main()
{
dynamic employeeName;
dynamic hourlySalary, weeklyTime, weeklySalary;
employeeName = "Patricia Katts";
hourlySalary = 22.75;
weeklyTime = 38.50;
weeklySalary = hourlySalary * weeklyTime;
Console.WriteLine("==============================");
Console.WriteLine("Payroll Summary");
Console.WriteLine("------------------------------");
Console.Write("Employee Name: ");
Console.WriteLine(employeeName);
Console.Write("Hourly Salary: ");
Console.WriteLine(hourlySalary);
Console.Write("Weekly Time: ");
Console.WriteLine(weeklyTime);
Console.Write("Weekly Salary: ");
Console.WriteLine(weeklySalary);
Console.WriteLine("==============================");
System.Console.ReadKey();
return 0;
}
}
- Execute the application:
==============================
Payroll Summary
------------------------------
Employee Name: Patricia Katts
Hourly Salary: 22.75
Weekly Time: 38.5
Weekly Salary: 875.875
==============================
- Press any key and return to your programming environment
The Microsoft Visual Basic Library
|
|
One of the strengths of Visual Basic, from its
beginning, was its huge library of functions. Unfortunately, when Visual
Basic was part of the Visual Studio 6.0 environment, its functions belonged
only to it and to its child languages such as VBA and VBScript. When
Microsoft Visual Studio .NET (2002) was created, the developers of Visual
Basic added all of its valuable functions, and in fact made them available,
to the other languages that use the .NET Framework. This means that those
wonderful functions are available for use in your C# programs.
The Visual Basic language is one of those languages that
have their own library of functions and classes. If you want to use that
library in a non-Visual Basic application, you must reference it in your
application. The functions of the Visual Basic language are created in the
Microsoft.VisualBasic.dll library. Based on this, you can include any
Visual Basic function in your program. To start, you can add its reference
in your application. After doing this, you can call the desired Visual Basic
function.
Application:
Using the Visual Basic Library
|
|
- To start a new project, on the main menu, click File -> New
Project...
- In the middle list, click Empty Project
- Change the Name to DepartmentStore7 and click Add
- On the main menu, click Project -> Add Reference...
- Cclick the .NET tab
- In the list, click Microsoft.VisualBasic
- Click OK
- In the Solution Explorer, right-click DepartmentStore7 -> Add -> New
Item...
- In the middle list, click Code File
- Change the name to CreditCardEvaluation and click
Add
- Change the file as follows:
using System;
public class Payroll
{
static int Main()
{
double presentValue = 500.00d;
double interestRate = 0.08627; // 8.627%
double numberOfPayments = 24; // 2 years * 12 months
double monthlyPayment = 0.00d;
monthlyPayment = Microsoft.VisualBasic.Financial.Pmt(interestRate,
numberOfPayments,
-presentValue);
Console.WriteLine("==========================");
Console.WriteLine("=-= Department Store =-=");
Console.WriteLine("-- Store Card Estimate --");
Console.WriteLine("--------------------------");
Console.Write("Starting Balance: ");
Console.WriteLine(Microsoft.VisualBasic.Strings.FormatNumber(presentValue));
Console.Write("Interest Rate: ");
Console.WriteLine(Microsoft.VisualBasic.Strings.FormatPercent(interestRate));
Console.Write("Monthly Payment: ");
Console.WriteLine(Microsoft.VisualBasic.Strings.FormatCurrency(monthlyPayment));
Console.WriteLine("==========================");
System.Console.ReadKey();
return 0;
}
}
- Execute the application. This would produce:
==========================
=-= Department Store =-=
-- Store Card Estimate --
--------------------------
Starting Balance: 500.00
Interest Rate: 8.63%
Monthly Payment: $50.00
==========================
- Press any key to close the DOS window and return to your programming
environment
One of the most important sought goals in .NET is to
allow different languages to collaborate, such as sharing code. One way this
can happen is to be able to use the functionality of one language into a
program create with another language. For example, you can use the rich
library of Visual Basic functions in a C# application. As no library is ever
complete, you may still need functionality that is not easily found in the
language you are using. Furthermore, you may be working with a team of
programmers who are using different languages and/or have already created a
set of functions or complex operations. You should be able to use that
existing code.
The Microsoft Windows operating system was originally
written in C, the parent language of C++ and C# (also of Java). To allow
programmers to create applications, Microsoft released a library called
Win32. This is a series of functions and classes, etc, that you previously
had to use. As time has changed, you do not need to exclusively use Win32
anymore to create a Windows application. Nonetheless, Win32 is still
everywhere and it is not completely avoidable because many or some of the
actions you would want to perform in a Windows application are still
available only in Win32. Fortunately, in most cases, it is not always
difficult to use some of these functions in a C# applications, as long as
you observe some rules. Here is an example:
using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport("Kernel32.dll")]
public static extern bool SetConsoleTitle(string strMessage);
static void Main()
{
SetConsoleTitle("C# Programming");
}
}
In previous years, it used to be a challenge to create a
library, especially in C++. Fortunately, Microsoft Visual C++ now makes it
particularly easy to create one, because a wizard highly assists you. To
create a library, first display the New Project dialog box. After specifying
Visual C++, in the middle list, click Class Library and give it a name. In
the body of the file, you can create the classes and/or functions as you see
fit. Here is an example:
// Business.h
#pragma once
using namespace System;
public ref class Finance
{
public:
double CalculateDiscount(double MarkedPrice,
double DiscountRate)
{
return MarkedPrice * DiscountRate / 100;
}
};
Once the project is ready, you must build it (on the
main menu, Build -> Build Business). As a result, the compiler would create
a file with the .dll extension:
Normally, as far as creating a library, that's it.
Creating a library in C++ is easy. To use it, there are
a few rules you must follow. To start, you must make sure that your project
can "physically" find the library. Probably the easiest way to take care of
this is to copy the dll file and paste it in the folder that contains your
project's executable. You can also do this directly in Microsoft Visual
Studio by importing the library file as we saw earlier.
In your project, you should include the
System.Runtime.InteropServices namespace. Before the section where the
library will be accessed, enter the DllImport attribute that takes as
argument the name of the library passed as a string. Here is an example:
using System;
using System.Runtime.InteropServices;
using Business;
class Exercise
{
[DllImport("Business.dll")]
public static extern double CalculateDiscount(double price,
double discount)
static int Main()
{
Finance fin = new Finance();
double markedPrice = 275.50;
double discountRate = 25.00; // %
double discountAmount = fin.CalculateDiscount(markedPrice,
discountDate);
double netPrice = markedPrice - discountAmount);
Console.Write("Marked Price: ");
Console.WriteLine("markedPrice);
Console.Write("Discount Rate: ");
Console.WriteLine("discountRate / 100);
Console.Write("Discount Amount: ");
Console.WriteLine("discountAmount);
Console.Write("Net Price: ");
Console.WriteLine("netPrice);
return 0;
}
}
Application:
Ending the Lesson
|
|
- Close your programming environment
- When asked whether you want to save, click No
|
|