Custom Libraries

Introduction

A library is a program that contains classes and/or other resources that some other programs can use. A library can be used to assist a computer language to perform one or various types of operations such as arithmetic calculations, scientific manipulations, medical tests, simulations, chemistry, artificial intelligence, drawing, 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.

To assist your projects with some types of operations, you can create a library and use it in one or more of your 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() method. A library usually has the extension .dll (other types of libraries in Microsoft Windows can have the extension .lib or another extension).

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.

Creating a Library

Microsoft Visual Studio makes it convenient to create a library, from scratch or as a project. You have various options for various goals, depending on the type of library you want and for the type of project that will use the library. To create a library project, first display the Create a New Project dialog box. In the list of projects templates, click Class Library.

Practical LearningPractical Learning: Introducing Custom Libraries

  1. Start Microsoft Visual Studio
  2. On the Visual Studio 2022 dialog box, click Create a New Project
  3. In the Create a New Project dialog box, make sure the selected language is C#.
    In the list of projects templates, click Class Library

    Create a New Project

  4. Click Next
  5. Change the Project Name to MetricSystem
  6. Click Next
  7. In the Framework combo box, make sure the .NET 7.0 (Standard Term Support) option is selected (if not, select it)
    Click Create
  8. In the Solution Explorer, right-click Class1.cs and click Rename
  9. Type Conversion (to get Conversion.cs)
  10. In the Code Editor, change the document as follows:
    using static System.Console;
    
    namespace MetricSystem
    {
        public class Conversion
        {
            public double Number { get; set; }
    
            public void InchesToCentimeters()
            {
                double result = Number * 2.54;
    
                Write(result);
            }
    
            public void CentimetersToInches()
            {
                double result = Number * 0.393701;
    
                Write(result);
            }
    
            public void FeetToMeters()
            {
                Write(Number * 0.3048);
            }
    
            public void MetersToFeet()
            {
                Write(Number * 3.2808);
            }
        }
    }
    
    namespace SquaredValues
    {
        public class Areas
        {
            public double Number { get; set; }
            
            public void SquaredInchesToCentimeters()
            {
                double result = Number * 6.4516;
                
                Write(result);
            }
            
            public void SquaredCentimetersToInches()
            {
                double result = Number * .155;
                
                Write(result);
            }
            
            public void AcreToHectare()
            {
                Write(Number * .4047);
            }
        }
    }
    
    namespace CubedValues
    {
        public class Volumes
        {
            public double Number { get; set; }
            
            public void LitreToGallons()
            {
                double result = Number * .2642;
                
                Write(result);
            }
        }
    }
  11. To make sure the project is configured as a library, on the main menu, click Project -> MetricSystem Properties
  12. Make sure the Output Type combo box is displaying Class Library

    Project Properties - Class Library

Building a Library

When you are creating a library and not an executable, you must build the project to create the actual library. To do that:

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.

After selecting the library, you can click Add.

In the Reference Manager dialog box, click OK. You can then use the classes and members of the library.

Practical LearningPractical Learning: Using a Custom Library

  1. To start a new project, on the main menu, click File -> New -> Project...
  2. In the list of projects templates, click Console App

    New Project

  3. Click Next
  4. Change the Name to ElementaryAlgebra2
  5. Make sure the Framework combo box is displaying .NET 7.0 (Standard Term Support). Click Create
  6. In the Solution Explorer, under ElementaryAlgebra2, right-click Dependencies and click Add Project Reference...
  7. In the bottom section of the dialog box, click the Browse... button
  8. Locate the folder where the library was created. Double-click the sub-folder of the same name as the project, followed by the bin sub-folder, followed by the Debug sub-folder
  9. Select MetricSystem.dll

    Reference Manager

  10. Click Add

    Reference Manager

  11. Click OK
  12. In the Solution Explorer, right-click Program.cs -> Rename
  13. Type ElementaryAlgebra (to get ElementaryAlgebra.cs)
  14. Change the document as follows:
    using static System.Console;
    using MetricSystem;
    
    Conversion converter = new Conversion();
    
    converter.Number = 124.475;
    
    WriteLine("Metric Conversion");
    WriteLine("=====================================");
    WriteLine("Inches to Centimeters");
    WriteLine("Number: {0} Inches", converter.Number);
    
    Write("Result: ");
    converter.InchesToCentimeters();
    WriteLine(" Centimeters");
    WriteLine("-------------------------------------");
    
    WriteLine("Centimeters to Inches");
    Write("Number: ");
    Write(converter.Number);
    WriteLine(" Centimeters");
    Write("Result: ");
    converter.CentimetersToInches();
    WriteLine(" Inches");
    WriteLine("-------------------------------------");
    
    WriteLine("Meters to Feet");
    Write("Number: ");
    Write(converter.Number);
    WriteLine(" Meters");
    Write("Result: ");
    converter.MetersToFeet();
    WriteLine(" Feet");
    WriteLine("=====================================");
    
    SquaredValues.Areas surfaces = new SquaredValues.Areas();
    
    surfaces.Number = converter.Number;
    
    WriteLine("Squared Inches to Squared Centimeters");
    Write("Number: ");
    Write(surfaces.Number);
    WriteLine(" Squared Inches");
    Write("Result: ");
    surfaces.SquaredInchesToCentimeters();
    WriteLine(" Squared Centimeters");
    WriteLine("-------------------------------------");
    
    WriteLine("Squared Centimeters to Squared Inches");
    Write("Number: ");
    Write(surfaces.Number);
    WriteLine(" Squared Centimeters");
    Write("Result: ");
    surfaces.SquaredCentimetersToInches();
    WriteLine(" Squared Inches");
    WriteLine("-------------------------------------");
    
    WriteLine("Acre to Hectare");
    Write("Number: ");
    Write(surfaces.Number);
    WriteLine(" Acres");
    Write("Result: ");
    surfaces.AcreToHectare();
    WriteLine(" Hectares");
    WriteLine("=====================================");
    
    CubedValues.Volumes vols = new CubedValues.Volumes();
    
    vols.Number = converter.Number;
    
    WriteLine("Litre to Gallons");
    Write("Number: ");
    Write(vols.Number);
    WriteLine(" Litres");
    Write("Result: ");
    vols.LitreToGallons();
    WriteLine(" Gallons");
    WriteLine("=====================================");
  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 Squared Centimeters
    Number: 124.475 Squared Inches
    Result: 803.06291 Squared Centimeters
    -------------------------------------
    Squared Centimeters to Squared Inches
    Number: 124.475 Squared Centimeters
    Result: 19.293625 Squared 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 close this window . . .
  16. Press any key to close the window and return to your programming environment

Introduction to Built-In Libraries

Introduction the .NET Framework

To assist programmers with their duties, Microsoft created a library named the .NET Framework, then created the .NET Core library. It is a huge library made of various classes aimed at different scenarios. When you are programming in C#, the primary library you must use is the .NET Core, or simply .NET. If the .NET does not provide a functionality you are looking for, you can create your own library and use it in your application(s). Still, before creating a library, make sure the .NET doesn't have the functionality you are looking for.

Using the .NET Library

The .NET library contains a tremendous number of classes. The classes are created in various namespaces. To use a class, first identify the class you want, then find out in which namespace the class exists. As seen in our introduction to namespaces, to indicate that you want to use a class that exists in a namespace, in the top section of the document, write the using keyword followed by the name of the namespace.

The .NET library is central to C#. To use a class of the .NET library in your C# application, you need to know what class contains the behavior you are looking for.

The Object Browser

The .NET is a very rich library. Its primary power is in its large set of classes. To organize these classes, the .NET library provides many namespaces. Each namespace is used to provide a specific set of classes.

To help you examine the namespaces of the .NET library, Microsoft Visual Studio provides the Object Browser. To access it, on the main menu, click View -> Object Browser. The Object Browser is made of three frames.

The left frame shows a list of libraries. To show the classes of a certain namespace, you should expand it, which is done by clicking its left triangular button. To see the list of members of a class, click its node:

Object Browser

Object Browser

To see the members (properties, methods, etc) of a class, click its node in the left frame. The central list would then display the members. Here is an example:

Object Browser

Introduction the System Namespace

The most fundamental namespace of the .NET is named System. It contains the primary data types you use in an application. It also contains the classes used in a regular application.

You will need the System namespace for almost every application you are creating. The primary way to use the System namespace in an application is to type the using keyword followed by System;. Here is an example:

using System;

class Exercise
{
    
}

An External Function

The .NET library is huge. It contains various types of objects you can use for your applications; but there are extreme cases where some functionality is not available. In that case, you can "borrow" functionality from other, external sources. One of the external sources you can use is a library named Win32. One of the resources that an external library like Win32 provides are functions.

To acccess a function from an external source, you use a keyword named extern.

Introduction to the C# Library

Introduction

The C# language has a small library made of just a few classes you probably 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.

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.

A Dynamic Variable

To let you declare dynamic variables, the C# language provides a keyword named dynamic. It is used as a data type. Here is an example of declaring a dynamic variable:

dynamic value;

You can initialize the variable when declaring it. The formula to follow is:

dynamic variable-name = desired-value;

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 Studio) that imports an external library.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2023, C# Key Sunday 14 November 2021 Next