Introduction to Libraries
Introduction to Libraries
Custom Libraries
Introduction
A library is a program that contains classes and/or other resources that other programs can use. A library is usually used to assist a computer language to perform one or various types of operations such as arithmetic calculations, scientific manipulations, medical tests, simulations, etc. Many languages use various types of libraries to assist them. Some languages have or include their own libraries. Some libraries are installed along with a language. Some other libraries must be acquired (and/or purchased) and installed separately.
The .NET Framework is a huge library made of various classes aimed at different scenarios. If the .NET Framework does not provide a functionality you are looking for, you can create you own library and use it in one or more programs. You can even create a commercial library and distribute or sell it.
There are various techniques to create a library but it is primarily created as a computer application. A library is not an executable; as a result, it doesn't include 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).
Practical Learning: Introducing Custom Libraries
A Library Contains Classes
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.
Libraries and Static Classes
When creating a class for your library, you can make that class a static one. If you do, when using the library in your code, you will not declare a variable for the class: You will use the class in your code and access its members directly from the name of the class.
Practical Learning: Starting a Library
namespace MetricSystem { public static class Conversion { public static double InchesToCentimeters(double number) { return number * 2.54; } public static double CentimetersToInches(double number) { return number * 0.393701; } public static double FeetToMeters(double number) { return number * 0.3048; } public static double MetersToFeet(double number) { return number * 3.2808; } } namespace SquaredValues { public static class Areas { public static double SquaredInchesToCentimeters(double number) { return number * 6.4516; } public static double SquaredCentimetersToInches(double number) { return number * .155; } public static double AcreToHectare(double number) { return number * .4047; } } namespace CubedValues { public static class Volumes { public static double LitreToGallons(double number) { return number * .2642; } } } } }
Creating a Library
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.
Practical Learning: Starting a Library
Building a Library
Since you would create a library and not an executable, to compile the project:
Practical Learning: Building a Library
Using a Custom Library
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 it. To do this:
In both cases, the Reference Manager 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 Add.
In the Reference Manager dialog box, you can click OK. You can then use the classes and methods of the library like you would use those of the .NET Framework.
Practical Learning: Using a Custom Library
using static System.Console; namespace Algebra1 { public class Algebra { public static int Main() { double value = 124.475; double converted = 0; converted = MetricSystem.Conversion.InchesToCentimeters(value); WriteLine("Metric Conversion"); WriteLine("====================================="); WriteLine("Inches to Centimeters"); Write("Number: "); Write(value); WriteLine(" Inches"); Write("Result: "); Write(converted); WriteLine(" Centimeters"); WriteLine("-------------------------------------"); converted = MetricSystem.Conversion.CentimetersToInches(value); WriteLine("Centimeters to Inches"); Write("Number: "); Write(value); WriteLine(" Centimeters"); Write("Result: "); Write(converted); WriteLine(" Inches"); WriteLine("-------------------------------------"); converted = MetricSystem.Conversion.MetersToFeet(value); WriteLine("Meters to Feet"); Write("Number: "); Write(value); WriteLine(" Meters"); Write("Result: "); Write(converted); WriteLine(" Feet"); WriteLine("-------------------------------------"); converted = MetricSystem.SquaredValues.Areas.SquaredInchesToCentimeters(value); WriteLine("Squared Inches to Centimeters"); Write("Number: "); Write(value); WriteLine(" Squared Inches"); Write("Result: "); Write(converted); WriteLine(" Centimeters"); WriteLine("-------------------------------------"); converted = MetricSystem.SquaredValues.Areas.SquaredCentimetersToInches(value); WriteLine("Squared Centimeters to Inches"); Write("Number: "); Write(value); WriteLine(" Squared Centimeters"); Write("Result: "); Write(converted); WriteLine(" Inches"); WriteLine("-------------------------------------"); converted = MetricSystem.SquaredValues.Areas.AcreToHectare(value); WriteLine("Acre to Hectare"); Write("Number: "); Write(value); WriteLine(" Acres"); Write("Result: "); Write(converted); WriteLine(" Hectares"); WriteLine("-------------------------------------"); converted = MetricSystem.SquaredValues.CubedValues.Volumes.LitreToGallons(value); WriteLine("Litre to Gallons"); Write("Number: "); Write(value); WriteLine(" Litres"); Write("Result: "); Write(converted); WriteLine(" Gallons"); WriteLine("====================================="); return 0; } } }
Metric Conversion ===================================== Inches to Centimeters Number: 124.475 Inches Result: 316.1665 Centimeters ------------------------------------- Centimeters to Inches Number: 124.475 Centimeters Result: 49.005931975 Inches ------------------------------------- Meters to Feet Number: 124.475 Meters Result: 408.37758 Feet ------------------------------------- Squared Inches to Centimeters Number: 124.475 Squared Inches Result: 803.06291 Centimeters ------------------------------------- Squared Centimeters to Inches Number: 124.475 Squared Centimeters Result: 19.293625 Inches ------------------------------------- Acre to Hectare Number: 124.475 Acres Result: 50.3750325 Hectares ------------------------------------- Litre to Gallons Number: 124.475 Litres Result: 32.886295 Gallons ===================================== Press any key to continue . . .
namespace Algebra { public class Arithmetic { 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; } } }
Introduction to Built-In Libraries
Introduction to the C# Library
Unlike many other languages, C# has only a tiny library made of just a few classes you will hardly use. The library is named Microsoft.CSharp.dll. 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 Reference Manager dialog box. To add it:
A data type communicates to the compiler how much memory it should reserve for the variable. 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. A dynamic variable is mostly used if you are creating a project that would communicate with an external 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.
Practical Learning: Using a Dynamic Variable
using static System.Console; public class Payroll { static int Main() { dynamic employeeName; dynamic hourlySalary, weeklyTime, weeklySalary; employeeName = "Patricia Katts"; hourlySalary = 22.75; weeklyTime = 38.50; weeklySalary = hourlySalary * weeklyTime; WriteLine("=============================="); WriteLine("Payroll Summary"); WriteLine("------------------------------"); Write("Employee Name: "); WriteLine(employeeName); Write("Hourly Salary: "); WriteLine(hourlySalary); Write("Weekly Time: "); WriteLine(weeklyTime); Write("Weekly Salary: "); WriteLine(weeklySalary); WriteLine("=============================="); ReadKey(); return 0; } }
============================== Payroll Summary ------------------------------ Employee Name: Patricia Katts Hourly Salary: 22.75 Weekly Time: 38.5 Weekly Salary: 875.875 ==============================
The Object Browser
The .NET Framework is a very rich, powerful, and expanded library. Its primary power is in its large set of classes. To organize these classes, the .NET Framework provides many namespaces. Each namespace is used to provide a specific set of classes.
To help you examine the namespaces of the .NET Framework, Microsoft Visual Studio provides the Object Browser. To access it, on the main menu, click View -> Object Browser. The Object is made of three frames.
The left frame shows a list of libraries. To show the content of a library, you can expand it, which is done by clicking its left triangular button. To see the list of namespaces created in a library, expand its library:
To see the list of classes that belong to the same namespace, expand that namespace. Here is an example:
Using the .NET Framework
The .NET Framework library is central to C#. That library includes hundreds of namespaces and thousands of classes or objects. One way or another, all those namespaces and classes are available to C#. This means that you have tremendous choices when programming in C#. To use a class of the .NET Framework in your C# application, you need to know what class contains the behavior you are looking for.
Using Microsoft Visual Basic in C#
Introduction
Besides C#, Visual Basic is another language that supports the .NET Framework was created. The Visual Basic language includes its own library of functions, which is huge. The Visual Basic functions are created in static classes of that language. You can use those functions in your C# code.
To use a Visual Basic function in your C# application, you must add reference to it. The functions of the Visual Basic language are created in the Microsoft.VisualBasic.dll library.
Practical Learning: Using the Visual Basic Library
using static System.Console; namespace DepartmentStore6 { public class DepartmentStore { public static int Main() { double presentValue = 500.00; double interestRate = 0.08627; // 8.627% double numberOfPayments = 24; // 2 years * 12 months double monthlyPayment = 0.00; monthlyPayment = Microsoft.VisualBasic.Financial.Pmt(interestRate, numberOfPayments, -presentValue); WriteLine("=========================="); WriteLine("=-= Department Store =-="); WriteLine("-- Store Card Estimate --"); WriteLine("--------------------------"); Write("Starting Balance: "); WriteLine(Microsoft.VisualBasic.Strings.FormatNumber(presentValue)); Write("Interest Rate: "); WriteLine(Microsoft.VisualBasic.Strings.FormatPercent(interestRate)); Write("Monthly Payment: "); WriteLine(Microsoft.VisualBasic.Strings.FormatCurrency(monthlyPayment)); WriteLine("=========================="); return 0; } } }
========================== =-= Department Store =-= -- Store Card Estimate -- -------------------------- Starting Balance: 500.00 Interest Rate: 8.63% Monthly Payment: $50.00 ==========================
My Visual Basic Namespace
Besides functions, the Visual Language performs many of its operations as services. Each service is created as a (Visual Basic) class. To make the services/classes available, the Visual Basic language provides a namespace named My. Fortunately, the language makes its services available to other .NET languages.
Before using a Visual Basic service, you must add a reference to the Microsoft.Visual.Basic.dll library. The Visual Basic services are created in various namespaces. To use a service, you must know its namespace. You can then add that namespace to the top of the file where you want to use it. Then, in the document that contains your code, declare a variable of the Visual Basic class you want to use.
Interoperability
Introduction
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"); } }
A Visual C++/CLI Library
You can use a library created in Microsoft Visual C++ in your C# code. 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.
Using the Library
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 static System.Console;
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);
Write("Marked Price: ");
WriteLine("markedPrice);
Write("Discount Rate: ");
WriteLine("discountRate / 100);
Write("Discount Amount: ");
WriteLine("discountAmount);
Write("Net Price: ");
WriteLine("netPrice);
return 0;
}
}
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2001-2019, FunctionX | Next |
|