A Custom Library

Introduction

A library is a program that contains classes and/or other resources that other programs can use. A library is mainly used to serve either other libraries and/or be used in various types of projects.

A library can be made of a single file or as many files as necessary. A file of a library can contain one or more classes. The class(es) can be created directly in the document or included in namespaces. Each class should implement a behavior that can eventually be useful and accessible to other classes.

Creating a Library

To manually create a library, start a text file and type the necessary code. Here is an example:

public class Algebra
{
    public decimal Addition(decimal x = 0, decimal y = 0)
    {
        return x + y;
    }

    public decimal Subtraction(decimal x = 0, decimal y = 0)
    {
        return x - y;
    }

    public decimal Multiplication(decimal x = 0, decimal y = 0)
    {
        return x * y;
    }

    public decimal Division(decimal x = 0, decimal y = 1)
    {
        return x / y;
    }
}

If you are using Microsoft Visual Studio, on the main menu, click File -> New -> Project... In the middle list, click a Class Library option. Then give it a name:

New Project

If you are using Microsoft Visual Studio, a starting code would be written for you and you can complete it as you see fit.

ApplicationPractical Learning: Introducing Custom Libraries

  1. Start Microsoft Visual Studio
  2. To start a new project, on the main menu, click File -> New -> Project...
  3. In the left list, under Visual C#, click .NET Standard
  4. In the middle list, click Class Library (.NET Standard)
  5. Change the Name to MetricSystem

    New Project

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

Building a Library

Before using a library, you must compile its file. This would create a file with a special extension. Most libraries have the extension .dll. In some cases, a library may have the extension .lib or another. When you build the library, the compiler creates that file and adds the necessary extension.

To compile a library at the Command Prompt, after the csc application, type /t:library. This means that you are creating (the target is) a library. Here is an example:

C:\Exercises>C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc /target:library MetricSystem.cs

You can also use t in place of target. Here are examples:

csc /t:library file-name.cs

Or:

csc /target:library file-name.cs

If you want a custom name for your library, use the following formula:

csc /target:library /out:DesiredNameOfLibrary.dll file-name.cs

If you are using Microsoft Visual Studio, to build a library:

ApplicationPractical Learning: Building a Library

Using a 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 any project of your choice. If you want to compile the project at the Command Prompt, after the csc application, type /r: followed by the name of the library file and its extension. This is followed by the name(s) of the file(s) of the current project. Here is an example:

C:\Exercises>C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc /r:MetricSystem.dll Exercise.cs

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:

In both cases, the Reference Manager dialog box would come up. You can click the Browse button, locate the folder where the library resides and select it.

After selecting the library, you can click OK or press Enter. You can then use the classes and methods of the library in your code.

ApplicationPractical Learning: Using a Library

  1. To start a new project, on the main menu, click File -> New -> Project...
  2. In the middle list, click ASP.NET Web Application (.NET Framework)
  3. Change the Name to MetricConversions1
  4. Click OK
  5. In the New ASP.NET Web Application, click the Empty icon
  6. Click Add
  7. In the Solution Explorer, right-click References -> Add Reference...
  8. In the middle list of Reference Manager, click the bottom Browse button
  9. Depending on where you add created the previous project, locate the folder where the library was created
  10. Select MetricSystem.dll

    Add Reference

  11. Click Add
  12. In the Reference Manager dialog box, click OK
  13. In the Solution Explorer, right-click MetricConversions1 -> Add -> New Item...
  14. In the left list of the Add New Item dialog box, click Razor and, in the middle list, click Web Page (Razor v3)
  15. Change the file Name to MetricConversions
  16. Click Add
  17. Change the file as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Metric Conversion</title>
    </head>
    <body>
    <h2>Metric Conversion</h2>
    
    @{
        decimal value = 0;
        decimal converted = 0;
    
        if (IsPost)
        {
            value = Request["txtNumber"].AsDecimal();
    
            converted = MetricSystem.Conversion.CentimetersToInches(value);
        }
    }
    
    <form name="MetricConversion" method="post">
        <table>
            <tr>
                <td>Number:</td>
                <td><input type="text" name="txtNumber" value="@value" /></td>
                <td>Centimeters</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input type="submit" name="btnConvert" value="Convert" /></td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>Result:</td>
                <td><input type="text" name="txtResult" value="@converted" /></td>
                <td>Inches</td>
            </tr>
        </table>
    </form>
    </body>
    </html>
  18. To execute the application and test it, press Ctrl + F5
    Using a Custom Library
  19. In the top text box, type a number, such as 226.84
  20. Click the button
    Using a Custom Library
  21. Close the browser and return to your programming environment

Introduction to the C# Library

Overview

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 C# 4.0 release of the language, the library was slightly updated and includes a new data type we can now use.

If you create a certain type of 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

    Add Referencce

  4. Click OK

The dynamic Data Type

In previous lessons, we used different data types (int, 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:

Data Type

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:

Data Type

Data Type

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:

@{
    dynamic value;
}

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:

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

Using Other Libraries

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

Microsoft Visual Basic Functions

Microsoft Visual Basic offers a very large set of functions. You can use most of those functions in your application if you follow the appropriate steps. To use a Microsoft Visual Basic function in your application, you must reference its library. Most (if not all) of the functions of Visual Basic are created in the Microsoft.VisualBasic.dll assembly but they might be in different namespaces. Based on this, you can include any Visual Basic function in your program.

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. Fortunately, in most cases, it is not always difficult to use some of these functions in a C# applications, as long as you follow 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");
    }
}

Introduction to Built-In Namespaces

Using the .NET Framework

The .NET Framework library is central to C#. That library includes hundreds of namespaces and thousands of classes or objects (available as static classes). 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. This comes with experience but mostly, you have to consult the highly documented .NET Framework. The document is available in various websites.

The Object Browser

The .NET Framework is a very rich, powerful, and expanded library. 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 Browser is made of three frames:

Object Browser

The left frame shows a list of libraries. Because most libraries contain more than one namespace, each node is equipped with a right-pointing triangular button. To expand a node, click the triangular button. After expanding a library, the namespaces it contains appear as nodes. Because most namespaces contain more than one class, each namespace is equipped with a right-pointing triangular button. To expand it, you can click the triangular button. After expanding a namespace, its list of classes appears. To show the members of a class, in the left frame, click it:

Object Browser

To get an explanation or description of a member of the class, in the top-middle frame, click that member. The bottom-right frame presents some information about the selected item.

Object Browser

Introduction to the System Namespace

The most regularly used namespace in the .NET Framework is called System. To use the System namespace, you can type it inside a method. You can also precede System with global and the :: operator.

We learned that, to access a namespace, you can use the using keyword. In the same way, you can use using to refer to the System namespace. Here is an example:

using System;

public class Exercise
{

}

This time too, you can precede System with global::

using global::System;

public class Exercise
{

}

Once you have used using System or using global::System, you can use or omit System in the body of the function.

ApplicationPractical Learning: Ending the Lesson


Previous Copyright © 2008-2019, FunctionX Next