Home

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 must 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 Add Reference dialog box.

 
 

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 extenal 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 and click Add
  4. In the Solution Explorer, right-click DepartmentStore6 -> Add -> New Item...
  5. In the middle list, click Code File
  6. Change the name to PayrollProcessing and click Add
  7. On the main menu, click Project -> Add Reference...
  8. In the Add Reference dialog box, click the .NET tab
  9. In the list, click Microsoft.CSharp
     
    Add Referencce
  10. Click OK
  11. 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;
    
            Console.WriteLine("==============================");
            Console.WriteLine("Payroll Summary");
            Console.WriteLine("------------------------------");
            Console.Write("Employee Name: ");
            Console.WriteLine(employeeName);
            Console.Write("Hourly Salary: ");
            Console.WriteLine(hourlySalary);
            Console.Write("Weekly Time:   ");
            Console.WriteLine(weeklyTime);
            Console.Write("Weekly Salary: ");
            Console.WriteLine(weeklySalary);
            Console.WriteLine("==============================");
    
            System.Console.ReadKey();
            return 0;
        }
    }
  12. Execute the application:
    ==============================
    Payroll Summary
    ------------------------------
    Employee Name: Patricia Katts
    Hourly Salary: 22.75
    Weekly Time:   38.5
    Weekly Salary: 875.875
    ==============================
  13. Press any key and return to your programming environment

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 and click Add
  4. On the main menu, click Project -> Add Reference...
  5. Cclick the .NET tab
  6. In the 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 and click Add
  11. 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,
                                                                 numberOfPayments,
                                                                 -presentValue);
            Console.WriteLine("==========================");
            Console.WriteLine("=-=  Department Store  =-=");
            Console.WriteLine("-- Store Card Estimate --");
            Console.WriteLine("--------------------------");
            Console.Write("Starting Balance: ");
            Console.WriteLine(Microsoft.VisualBasic.Strings.FormatNumber(presentValue));
            Console.Write("Interest Rate:    ");
            Console.WriteLine(Microsoft.VisualBasic.Strings.FormatPercent(interestRate));
            Console.Write("Monthly Payment:  ");
            Console.WriteLine(Microsoft.VisualBasic.Strings.FormatCurrency(monthlyPayment));
            Console.WriteLine("==========================");
    
            System.Console.ReadKey();
            return 0;
        }
    }
  12. Execute the application. 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

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

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
{
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 System;
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);

        Console.Write("Marked Price:    ");
	Console.WriteLine("markedPrice);
        Console.Write("Discount Rate:   ");
	Console.WriteLine("discountRate / 100);
        Console.Write("Discount Amount: ");
	Console.WriteLine("discountAmount);
        Console.Write("Net Price:       ");
	Console.WriteLine("netPrice);

	return 0;
    }
}

ApplicationApplication: Ending the Lesson

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

Previous Copyright © 2010-2011 FunctionX Next