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;
  2. namespace LibraryUtil
  3. {
  4. public class MathLib
  5. {
  6. public MathLib() { }
  7. public int Sum(int x, int y)
  8. {
  9. int z = x + y;
  10. return z;
  11. }
  12. }
  13. }

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
  3. namespace oops
  4. {
  5. public class LibraryClass
  6. {
  7. static void Main()
  8. {
  9. //library class instance
  10. MathLib obj = new MathLib();
  11. //invoke Sum method
  12. Console.WriteLine(obj.Sum(12, 13));
  13. }
  14. }
  15. }

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