OOP Series - Part One - Building And Consuming A Class Library (DLL) Using C#

The first step in Object Oriented Programming is to learn how to create a DLL because most of the reusable components are written in the form of a DLL (Dynamic Link Library).

.NET provides you the option to create libraries (components) that are not “.exe” executables. Instead, the Class Library project final build output will be a “.dll” that can be referenced by other applications to expose its entire functionality.

Build a DLL

Step 1

First, create a project of type “Class Library” as shown here.

Building and Consuming a Class Library (DLL) Using C#

Step 2
Then we are implementing a Math class library that is responsible for calculating the sum of two numbers.
  1. using System;  
  3. namespace LibraryUtil  
  4. {  
  5.     public class MathLib  
  6.     {  
  7.         public MathLib() { }  
  9.         public int Sum(int x, int y)  
  10.         {  
  11.             int z = x + y;
  13.             return z;  
  14.         }          
  15.     }  

Step 3

Build this code and you will see that a DLL file has been created rather than an exe in the root directory of the application (path = D:\temp\LibraryUtil\LibraryUtil\bin\Debug\ LibraryUtil.dll)

Consume the DLL

Step 1
Now create another console based application where we will utilize the class library functionality.

Step 2
Then you need to add the reference of the Math Class Library DLL file reference to access the declared class in the library DLL. (Right-click on the Reference then select Add reference then select the path of the DLL file.)

Step 3
When you add the class library reference then you will see in the Solution Explorer that a new LibraryUtil is added as in the following,

Building and Consuming a Class Library (DLL) Using C#

Step 4
Now add the namespace of the class library file in the console application and create the instance of the class declared in the library as follows,
  1. using System;  
  2. using LibraryUtil; // add library namespace  
  4. namespace oops  
  5. {  
  6.     public class LibraryClass  
  7.     {  
  8.         static void Main()  
  9.         {  
  10.             //library class instance  
  11.             MathLib obj = new MathLib();  
  13.             //invoke Sum method  
  14.             Console.WriteLine(obj.Sum(12, 13));              
  15.         }  
  16.     }  

Step 5

Finally, run the application and you must see the result as shown in the image below.

Building and Consuming a Class Library (DLL) Using C#

YouTube Video