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 ("class1.cs") to "calculate.cs".
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 "calculation.dll" 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, "calculation.dll", 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 System.Collections.Generic;
3. using System.ComponentModel;
4. using System.Data;
5. using System.Drawing;
6. using System.Linq;
7. using System.Text;
8. using System.Windows.Forms;
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 = cal.Add(int.Parse(txtFirstNo.Text), int.Parse(txtSecNo.Text));
28. txtResult.Text = i.ToString();
29. }
30.
31. catch (Exception ex)
32. {
33. MessageBox.Show(ex.Message);
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 = cal.Sub(int.Parse(txtFirstNo.Text), int.Parse(txtSecNo.Text));
45. txtResult.Text = i.ToString();
46. }
47. catch (Exception ex)
48. {
49. MessageBox.Show(ex.Message);
50. }
51. }
52. }
53.