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

Practical LearningPractical Learning: Introducing Custom Libraries

  1. Start Microsoft Visual Studio and, in the Visual Studio 2022 dialog box, click Create a New Project (if Microsoft Visual Studio had already started, on the main menu, click File -> New -> Project...)
  2. In the Create a New Project dialog box, make sure C# selected in the Languages combo box.
  3. In the list of project templates, click Class Library

    Introducing to Libraries

  4. Click Next
  5. Change the Name to MetricSystem

    Introducing to Libraries

  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 Next
  7. In the Additional Information wizard page, make sure the Framework combo box is displaying .NET 7.0 (Standard Term Support)

    Addition Information

    Click Create
  8. In the Solution Explorer, right-click Class1 -> Rename
  9. Type Conversion (to get Conversion.cs) and press Enter
  10. Read the message on the message box and click Yes
  11. Change the document as follows:
    namespace MetricSystem
    {
        public class Conversion
        {
            public double number;
    
            public double InchesToCentimeters()
            {
                 return number * 2.54;
            }
    
            public double CentimetersToInches()
            {
                return number * 0.393701;
            }
    
            public double FeetToMeters()
            {
                return number * 0.3048;
            }
    
            public double MetersToFeet()
            {
                return number * 3.2808;
            }
        }
    
        namespace SquaredValues
        {
            public class Areas
            {
                public double number;
    
                public double SquaredInchesToCentimeters()
                {
                     return number * 6.4516;
                }
    
                public double SquaredCentimetersToInches()
                {
                    return number * .155;
                }
    
                public double AcreToHectare()
                {
                    return number * .4047;
                }
            }
        }
    
        namespace CubedValues
        {
            public class Volumes
            {
                public double number;
    
                public double LitreToGallons()
                {
                     return number * .2642;
                }
            }
        }
    }

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.

Practical LearningPractical Learning: Checking a Library

  1. To check that you are creating a library, on the main menu, click Project -> MetricSystem Properties
  2. 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. In the Solution Explorer, under ElementaryAlgebra1, right-click Dependencies and click Add Project Reference...

    Reference Manager

  2. In the bottom section of the dialog box, click the Browse... button
  3. 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
  4. Select MetricSystem.dll

    Reference Manager

  5. Click Add

    Reference Manager

  6. Click OK
  7. In the Solution Explorer, right-click Pages -> Add -> Razor Page...
  8. In the middle list of the Add New Scaffolded Item dialog box, make sure Razor Page - Empty is selected.
    Click Add
  9. Change the file Name to Calculations
  10. Press Enter
  11. Change the document as follows:
    @page
    @model ElementaryAlgebra1.Pages.CalculationsModel
    @using MetricSystem
    @using MetricSystem.CubedValues
    @using MetricSystem.SquaredValues
    @{
        Conversion converter = new Conversion();
        
        converter.number = 124.475;
    
        Areas surfaces = new Areas();
    
        surfaces.number = converter.number;
        
        Volumes vols = new Volumes();
        
        vols.number = converter.number;
    }
    
    <pre>Metric Conversion
    =====================================
    Inches to Centimeters
    -------------------------------------
    Number: @converter.number Inches
    Result: @converter.InchesToCentimeters() Centimeters
    -------------------------------------
    Centimeters to Inches
    -------------------------------------
    Number: @converter.number Centimeters
    Result: @converter.CentimetersToInches() Inches
    -------------------------------------
    Meters to Feet
    -------------------------------------
    Number: @converter.number Meters
    Result: @converter.MetersToFeet() Feet
    =====================================
    
    Squared Inches to Squared Centimeters
    -------------------------------------
    Number: @surfaces.number Squared Inches
    Result: @surfaces.SquaredInchesToCentimeters() Squared Centimeters
    -------------------------------------
    
    Squared Centimeters to Squared Inches
    -------------------------------------
    Number: @surfaces.number Squared Centimeters
    Result: @surfaces.SquaredCentimetersToInches() Squared Inches
    -------------------------------------
    Acre to Hectare
    -------------------------------------
    Number: @surfaces.number Acres
    Result: @surfaces.AcreToHectare() Hectares
    =====================================
    
    Litre to Gallons
    -------------------------------------
    Number: @vols.number Litres
    Result: @vols.LitreToGallons() Gallons
    =====================================</pre>
  12. To execute the project and test it, 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.375032499999996 Hectares
    =====================================
    
    Litre to Gallons
    -------------------------------------
    Number: 124.475 Litres
    Result: 32.886295 Gallons
    =====================================
  13. Return to your programming environment

Introduction to Built-In Libraries

Introduction the .NET Library

To assist programmers with their duties, Microsoft created a library named the .NET Framework. 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 Framework. From now on, in our lessons, we we will use the name ".NET library". If the .NET library 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 library 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 Object Browser

The .NET Framework is a very rich 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, right-click the desired node in the left list and click View Namespaces:

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 library 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;.

Introduction to the Console

Introduction

One of the classes created in the System namespace is named Console. This is the most fundamental class used for an application that displays some text in a black window. To use the Console class in a razor page, you can type @using System in the top section of the razor page document. Then, in a @{} section, type Console. You can also use System.Console.

The System.Console class is created in a library named System.Console.dll. When you create a C# application in Microsoft Visual Studio, the System.Console.dll library is automatically included so you don't have to add it to your project.

Writing to the Console

The System.Console class is equipped with various methods. One method is named Write. In its parentheses, you can include the value you want to display. As mentionned already, in a document where you want to call a method of the Console class, you can type Console. followed by the name of the method and its parentheses. Here is an example:

@using System

@{
    Console.Write("Welcome to the World of C# Programming!");
}

Creating a New Line

In the parentheses of the Write() method, you can include the name of a variable. The Write() method displays its value and keeps the caret on the same line. Another method of the Console class is named WriteLine. This method takes 0 or more values as arguments. When the WriteLine() method has displayed nothing or a value, it continues with the caret on the next line.

Removing Unused Usings

Whenever you create a project in Microsoft Visual Studio using one of the non-Empty templates, the studio writes some primary code in the files that it creates. In the same way, the studio adds some using lines in the files. In most cases, you will not use some of the namespaces that are added, or you will know that some of the namespaces are not necessary for your file. As a matter of fact, by analyzing the content of each document, Microsoft Visual Studio knows when a namespace is not used in a document. The text of a namesoace that is not used is blurred as compared to the names of the namespaces that are used.

When a namespace is not used in your code, you should remove that namespace and its line. You can manually delete the line of a namespace but you could make a mistake when deleting such a line. Fortunately, Microsoft Visual Studio can assist you. To remove all the unused namespaces, right-click the section of usings and click Remove and Sort Usings.

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. 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 that 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