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 LearningPractical Learning: Introducing Custom Libraries

  1. Start Microsoft Visual C#
  2. To start a new application, on the main menu, click File -> New -> Project...
  3. In the left list of the New Project dialog box, under Visual C#, click Windows Desktop
  4. In the middle list, click Empty Project (.NET Framework)
  5. Change the Name to MetricSystem and

    New Project

  6. 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 OK

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 LearningPractical Learning: Starting a Library

  1. In the Solution Explorer, right-click MetricSystem -> Add -> Class...
  2. In the middle frame of the New Item dialog box, make sure Class is selected. Change the name to Conversion
  3. Click Add
  4. Chang ethe document as follows:
    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 LearningPractical Learning: Starting a Library

  1. On the main menu, click Project -> MetricSystem Properties...
  2. In the Output Type combo box, select Class Library

    Properties

Building a Library

Since you would create a library and not an executable, to compile the project:

Practical LearningPractical 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:

Add Reference

After selecting the library, you can click Add.

Add Reference

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 LearningPractical Learning: Using a Custom Library

  1. To start a new project, on the main menu, click File -> New -> Project...
  2. In the middle list, click Empty Project (.NET Framework)
  3. Change the Name to Algebra1
  4. Click OK
  5. In the Solution Explorer, under Algebra1, right-click References and click Add Reference...

    Add Reference

  6. In the bottom section of the dialog box, click the Browse... button
  7. Locate the folder where the library was created
  8. Select MetricSystem.dll
  9. Click Add
  10. Click OK
  11. In the Solution Explorer, right-click DepartmentStore5 -> Add -> Class...
  12. In the middle list, make sure Class is selected.
    Change the name to Algebra
  13. Click Add
  14. Change the document as follows:
    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;
            }
        }
    }
  15. To execute the application, on the main menu, click Debug -> Start Without Debugging:
    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 . . .
  16. Press any key and return to your programming environment
  17. For another technique to create a library, on the main menu of Microsoft Visual Studio, click File -> New -> Project...
  18. In the middle frame of the New Project dialog box, click Class Library (.NET Framework)
  19. Change the project Name to Algebra
  20. Click OK
  21. In the Solution Explorer, right-click Class1.cs and click Rename
  22. Type Arithmetic to get Arithmetic.cs, and press Enter
  23. Chang the document as follows:
    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;
            }
        }
    }
  24. To create the library, in the Solution Explorer, right-click Algebra -> Build

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:

  1. On the main menu, click Project -> Add Reference... Alternatively, in the Solution Explorer, right-click References and click Add Reference...
  2. In the Reference Manager dialog box, click Assemblies
  3. In the list, click Microsoft.CSharp
  4. Click OK

The dynamic Data Type

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 LearningPractical Learning: Using a Dynamic Variable

  1. To start a new project, on the main menu, click File -> New -> Project...
  2. In the middle list, click Empty Project (.NET Framework)
    Change the Name to DepartmentStore5
  3. Click Add
  4. On the main menu, click Project -> Add Reference...
  5. In the Reference Manager dialog box, click Assemblies
  6. In the middle list, click the check box of Microsoft.CSharp

    Add Referencce

  7. Click OK

    Introducing Loops

  8. In the Solution Explorer, right-click DepartmentStore5 -> Add -> New Item...
  9. In the left list of the Add New Item dialog box, under Visual C#, click Code and, in the midddle list, click Code File
  10. Change the name to DepartmentStore
  11. Click Add
  12. Change the file as follows:
    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;
        }
    }
  13. Execute the application:
    ==============================
    Payroll Summary
    ------------------------------
    Employee Name: Patricia Katts
    Hourly Salary: 22.75
    Weekly Time:   38.5
    Weekly Salary: 875.875
    ==============================
  14. Press any key and return to your programming environment

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:

Object Browser

To see the list of classes that belong to the same namespace, expand that namespace. Here is an example:

Object Browser

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 LearningPractical Learning: Using the Visual Basic Library

  1. To start a new project, on the main menu, click File -> New -> Project...
  2. In the middle list, click Empty Project (.NET Framework)
  3. Change the Name to DepartmentStore6
  4. Click Add
  5. On the main menu, click Project -> Add Reference...
  6. On the side, click Framework if ncessary.
    In the middle list, click Microsoft.VisualBasic

    Add Referencce

  7. Click OK
  8. In the Class View, right-click DepartmentStore6 -> Add -> Class...
  9. In the middle list, make sure Class is selected.
    Change the name to DepartmentStore
  10. Click Add
  11. Change the document as follows:
    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;
            }
        }
    }
  12. To execute the application, on the main menu, click Debug -> Start Without Debugging. This would produce:
    ==========================
    =-=  Department Store  =-=
    -- Store Card Estimate --
    --------------------------
    Starting Balance: 500.00
    Interest Rate:    8.63%
    Monthly Payment:  $50.00
    ==========================
  13. Press any key to close the DOS window and return to your programming environment

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 Win32 Library

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 LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2019, FunctionX Next