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
1. First create a project of type “Class Library” as shown here:
2. Then we are implementing a Math class library that is responsible of the calculating sum of two numbers as:
- using System;
-
- namespace LibraryUtil
- {
- public class MathLib
- {
- public MathLib() { }
-
- public int Sum(int x, int y)
- {
- int z = x + y;
- }
- }
- }
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
1. Now create another console based application where we will utilize the class library functionality.
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.)
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:
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:
- using System;
- using LibraryUtil;
-
- namespace oops
- {
- public class LibraryClass
- {
- static void Main()
- {
-
- MathLib obj = new MathLib();
-
-
- Console.WriteLine(obj.Sum(12, 13));
- }
- }
- }
5. Finally run the application and you must see the result as shown in the image below.
YouTube Video
https://www.youtube.com/watch?v=9YpxYI45iq