Custom Libraries


The .NET Framework is a huge library made of various classes aimed at different scenarios. We will explore some of these classes in our lessons. Still, 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. For example, you can "package" one or more classes in a library.

A library is a program that contains classes and/or other resources that other programs can use. Such a program is created with the same approach as the programs we have done so far. Because a library is not an executable, it does not need 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).

ApplicationApplication: 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, click Windows
  4. In the right list, click Empty Project
  5. Change the Name to SaleRecord and
    New Project
  6. Click OK
  7. To save the project, on the Standard toolbar, click the Save All button Save All
  8. If you accept the suggest folder (in the Location), make a note of it. Otherwise, enter a different location and keep it in mind
  9. Click Save

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.

To create a library, on the main menu of Microsoft Visual Studio, you can click FILE -> New -> Project... In the middle list, you can click Empty Project or click Class Library. Then give it a name:

New Project

If you had selected Empty Project in the New Project dialog box, you should open the Properties window and, in the Output Type combo box, select Class Library:


In both cases, a skeleton code would be presented to you and you can complete it as you see fit. Here is an example:

public class Algebra
        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;

ApplicationApplication: Starting a Library

  1. On the main menu, click PROJECT -> SaleRecord Properties...
  2. In the Output Type combo box, select Class Library
  3. To create a new file, on the main menu, click PROJECT -> Add New Item...
  4. In the left list, click Code
  5. In the right list, click Code File
  6. Change the Name to StoreItem and click Add
  7. Change the document as follows:
    public class StoreItem
        public int     itemNumber;
        public string  itemName;
        public string  size;
        public decimal unitPrice;
  8. On the Standard toolbar, click the Save All button Save All

Building a Library

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

If you want to compile a library at the Command Prompt, you would type:

csc /target:library NameOfFile.cs

and press Enter.

ApplicationApplication: 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 the library. 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 OK. You can then use the classes and methods of the library like you would use those of the .NET Framework. Here is an example:

using System;

public class Exercise
    static void Main()
	Algebra alg = new Algebra();

        double number1 = 244.58;
        double number2 = 5082.88;
        double result = alg.Addition(number1, number2);

        Response.Write(" + ");
        Response.Write(" = ");

If you want to compile the project at the Command Prompt, you would type something like the following:

csc /target:library /out:DesiredNameOfLibrary.dll NameOfFile.cs

This would produce:

244.58 + 5082.88 = 5327.46

Press any key to continue . . .

ApplicationApplication: 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
  3. Change the Name to DepartmentStore5
  4. Click OK
  5. In the Solution Explorer, under DepartmentStore5, right-click References and click Add Reference...
  6. Click the Browse tab
  7. Locate the folder where the library was created
  8. Select SaleRecord.dll
  9. Click Add
  10. Click OK
  11. In the Solution Explorer, right-click DepartmentStore5 -> Add -> New Item...
  12. In the middle list, click Code File
  13. Change the name to DepartmentStore
  14. Click Add
  15. Change the file as follows:
    using System;
    public class Program
        static int Main()
            StoreItem si = new StoreItem();
            si.itemNumber = 660284;
            si.itemName = "Tropical Wool Neutral Jacket";
            si.unitPrice = 200.00M;
            Response.Write("Store Inventory");
            Response.Write("Item #:     ");
            Response.Write("Item Name:  ");
            Response.Write("Unit Price: ");
            return 0;
  16. Execute the application:
    Store Inventory
    Item #:     660284
    Item Name:  Tropical Wool Neutral Jacket
    Unit Price: 200.00
    Press any key to continue . . .
  17. Press any key and return to your programming environment

Introduction to Built-In Libraries

Introduction to the C# Library

Unlike many other languages such as C++ or (Object) Pascal (Delphi), C# is known as being one of the languages that don't have their own library. This is not an anomaly and it doesn't make C# less efficient than any other language. That's just the way the language was designed. In fact, you will find out in this and other lessons that C# can benefit from using the libraries in the other languages, thanks to its tremendous flexibility.

In reality, 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 new 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 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
    Add Referencce
  4. Click OK

The dynamic Data Type

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

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

ApplicationApplication: 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
  3. Change the Name to DepartmentStore6
  4. Click Add
  5. In the Solution Explorer, right-click DepartmentStore6 -> Add -> New Item...
  6. In the middle list, click Code File
  7. Change the name to PayrollProcessing
  8. Click Add
  9. On the main menu, click PROJECT -> Add Reference...
  10. In the Reference Manager dialog box, click Assemblies
  11. In the list, click Microsoft.CSharp
  12. Click OK
  13. Change the file as follows:
    using System;
    public class Payroll
        static int Main()
            dynamic employeeName;
            dynamic hourlySalary, weeklyTime, weeklySalary;
            employeeName = "Patricia Katts";
            hourlySalary = 22.75;
            weeklyTime = 38.50;
            weeklySalary = hourlySalary * weeklyTime;
            Response.Write("Payroll Summary");
            Response.Write("Employee Name: ");
            Response.Write("Hourly Salary: ");
            Response.Write("Weekly Time:   ");
            Response.Write("Weekly Salary: ");
            return 0;
  14. Execute the application:
    Payroll Summary
    Employee Name: Patricia Katts
    Hourly Salary: 22.75
    Weekly Time:   38.5
    Weekly Salary: 875.875
  15. Press any key and return to your programming environment

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, starting with MSDN.

Again, in order to use a class, you must know in what library, called assembly, that class is defined. Once you know that assembly, if you are compiling your project from the Command prompt, type /reference: or /r: followed by the name of the library. Here is an example:

Using the .NET Framework

One of the objects you can use from the .NET Framework is a message box. A message box is a rectangular object that displays a message and can have some options. The message box is defined in a static class named MessageBox. The MessageBox class is defined in the System.Windows.Forms namespace that is a member of the System.Windows.Forms.dll assembly..

The MessageBox class is equipped with a method named Show that is used to hold the message to present to the user. The MessageBox.Show() method is overloaded with different versions to support various options. The simplest version takes only one argument as a string, which is the message to present to the user. The syntax of that version is:

public static DialogResult Show(string text);

To use this version of the MessageBox.Show(), put the desired message with double-quotes to the parentheses. Here is an example:

MessageBox.Show("Welcome to the wonderful world of C# programming!");

You can then execute the application. Here is an example:

Message Box

If you create a console application and you want to use a message box, make sure you add a reference to the System.Windows.Forms.dll library in your project.

The Microsoft Visual Basic Library

One of the strengths of Visual Basic, from its beginning, was its huge library of functions. Unfortunately, when Visual Basic was part of the Visual Studio 6.0 environment, its functions belonged only to it and to its child languages such as VBA and VBScript. When Microsoft Visual Studio .NET (2002) was created, the developers of Visual Basic added all of its valuable functions, and in fact made them available, to the other languages that use the .NET Framework. This means that those wonderful functions are available for use in your C# programs.

The Visual Basic language is one of those languages that have their own library of functions and classes. If you want to use that library in a non-Visual Basic application, you must reference it in your application. The functions of the Visual Basic language are created in the Microsoft.VisualBasic.dll library. Based on this, you can include any Visual Basic function in your program. To start, you can add its reference in your application. After doing this, you can call the desired Visual Basic function.

ApplicationApplication: 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
  3. Change the Name to DepartmentStore7
  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 Solution Explorer, right-click DepartmentStore7 -> Add -> New Item...
  9. In the middle list, click Code File
  10. Change the name to CreditCardEvaluation
  11. Click Add
  12. Change the file as follows:
    using System;
    public class Payroll
        static int Main()
            double presentValue = 500.00d;
            double interestRate = 0.08627; // 8.627%
            double numberOfPayments  = 24; // 2 years * 12 months
            double monthlyPayment = 0.00d;
            monthlyPayment = Microsoft.VisualBasic.Financial.Pmt(interestRate,
            Response.Write("=-=  Department Store  =-=");
            Response.Write("-- Store Card Estimate --");
            Response.Write("Starting Balance: ");
            Response.Write("Interest Rate:    ");
            Response.Write("Monthly Payment:  ");
            return 0;
  13. Execute the application. This would produce:
    =-=  Department Store  =-=
    -- Store Card Estimate --
    Starting Balance: 500.00
    Interest Rate:    8.63%
    Monthly Payment:  $50.00
  14. Press any key to close the DOS window and return to your programming environment



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
    public static extern bool SetConsoleTitle(string strMessage);

    static void Main()
        SetConsoleTitle("C# Programming");

A Visual C++/CLI Library

In previous years, it used to be a challenge to create a library, especially in C++. Fortunately, Microsoft Visual C++ now makes it particularly easy to create one, because a wizard highly assists you. 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
    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 System;
using System.Runtime.InteropServices;
using Business;

class Exercise
    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,
        double netPrice = markedPrice - discountAmount);

        Response.Write("Marked Price:    ");
        Response.Write("Discount Rate:   ");
	Response.Write("discountRate / 100);
        Response.Write("Discount Amount: ");
        Response.Write("Net Price:       ");

	return 0;

ApplicationApplication: Ending the Lesson

  1. Close your programming environment
  2. When asked whether you want to save, click No

Previous Copyright © 2008-2016, FunctionX Next