Creating and Using DLL (Class Library) in C#
Introduction
A Dynamic Link library (DLL) is a library that contains functions and codes that can be used by more than
one program at a time. Once we have created a DLL file, we can use it in many applications. The only
thing we need to do is to add the reference/import the DLL File. Both DLL and .exe files are executable
program modules but the difference is that we cannot execute DLL files directly.
Creating DLL File
Step 1 - Open Visual Studio then select "File" -> "New" -> "Project..." then seelct "Visual C#" -> "Class
library".
(I give it the name "Calculation".)
Step 2 - Change the class name ("[Link]") to "[Link]".
Step 3 - In the calculate class, write methods for the addition and subtraction of two integers (for example
purposes).
Step 4 - Build the solution (F6). If the build is successful then you will see a "[Link]" file in the
"bin/debug" directory of your project.
We have created our DLL file. Now we will use it in another application.
Using DLL File
Step 1 - Open Visual Studio then select "File" -> "New" -> "Project..." then select "Visual C#" ->
"Windows Forms application".
Step 2 - Design the form as in the following image:
Step 3 - Add a reference for the dll file, "[Link]", that we created earlier. Right-click on the project
and then click on "Add reference".
Step 4 - Select the DLL file and add it to the project.
After adding the file, you will see that the calculation namespace has been added (in references) as in the
following:
Step 5 - Add the namespace ("using calculation;") as in the following:
Step 6
1. using System;
2. using [Link];
3. using [Link];
4. using [Link];
5. using [Link];
6. using [Link];
7. using [Link];
8. using [Link];
9. using Calculation;
10.
11. namespace MiniCalculator
12. {
13. public partial class Form1 : Form
14. {
15.
16. public Form1()
17. {
18. InitializeComponent();
19. }
20. calculate cal = new calculate();
21. //Addition Button click event
22. private void button1_Click(object sender, EventArgs e)
23. {
24. try
25. {
26. //storing the result in int i
27. int i = [Link]([Link]([Link]), [Link]([Link]));
28. [Link] = [Link]();
29. }
30.
31. catch (Exception ex)
32. {
33. [Link]([Link]);
34. }
35. }
36.
37. //Subtraction button click event
38.
39. private void button2_Click(object sender, EventArgs e)
40. {
41. Try
42. {
43. //storing the result in int i
44. int i = [Link]([Link]([Link]), [Link]([Link]));
45. [Link] = [Link]();
46. }
47. catch (Exception ex)
48. {
49. [Link]([Link]);
50. }
51. }
52. }
53.