A Dynamic Link Library (DLL) is a file that can be used by other programs dynamically. It is a library that contains code, functions and data that can be used in another program or more than one program. So once we have created a DLL file, we can use it in many applications. The major advantage of DLL is that it doesn’t get loaded into memory with the program. It will load into memory when we use it or when we call it in our application. So DLLs are usually loaded on demand. DLL is also used to hide the code so that anyone can use only the functionality but not the code.
To use a DLL or code of the DLL in our application, only thing we need to do is to add the reference of that DLL in our application. When we have some reusable code and we need to use it in more than one application, we can create a DLL and put our code in that DLL. Then we can add a reference of that DLL in our application to use functions of that DLL. Both DLL and exe files are executable programs but the difference is that a DLL cannot be executed directly or independently.
There are few steps to create a DLL, we will see these steps in this article and also we will see how we can use this DLL in our application.
- Open Visual Studio and create a new Class Library Project in C#
- Rename the project to CreateDLL and rename the class to EmployeeClass.cs
Now write below code in Employee Class
// First method to get employee name
public string GetEmployeeName(int id)
{
string name = "";
switch (id)
{
case 1:
name = "Richard Wand";
break;
case 2:
name = "Susan Jacob";
break;
default:
name = "";
break;
}
return name;
}
// second method to get Salary
public int GetSalary(int id)
{
int salary = 0;
switch (id)
{
case 1:
salary = 27500;
break;
case 2:
salary = 35700;
break;
default:
salary = 0;
break;
}
return salary;
}
Now build solution to create CreateDLL .dll file. You can see this file in debug directory under bin.
Now we will see how we can use this DLL in our application
- Create a new website in Visual Studio
- Go to Solution Explorer and right click on project and click on Add Reference
- Go to Browse tab and find the CreateDLL.dll file and click Ok to add it in your website.
- Add a web form and write below controls in Default.aspx file.
asp:Label>
asp:Label>
Don’t forget to add following namespace in your Default.aspx.cs file
using CreateDLL;
Now write below code in your file
protected void Page_Load(object sender, EventArgs e)
{
EmployeeClass ObjEmp = new EmployeeClass();
string name = ObjEmp.GetEmployeeName(1);
lblName.Text = "Welcome " + name;
}
protected void btnGetSalary_Click(object sender, EventArgs e)
{
EmployeeClass ObjEmp = new EmployeeClass();
int salary = ObjEmp.GetSalary(1);
lblSalary.Text = "Your Salary is: $" + salary.ToString();
}
Debug the code and see it in your browser.