[C#]Creating and using .dll files


Yesterday in my college during System Software class we were learning about Dynamic Loaders. And the lecturer said some stuff about DLL files. Most people dont realize what a dll file is and how simple it is to create and use one in their programs. I came across programming dlls when I was learning C#.NET. DLL files are just code files that cant run alone. They support other programs. For instance you can store some classes in a dll file and you can link this file to any number of programs you want. And whenever your program wants the class it can just call the dll and it will be loaded @ runtime. Using dlls also reduces the amount of space your code occipies on disk since you are sharing the same dll among many programs. And it also allows modular programming. Anyway, I need not explain much about the advantages of using dlls since its well documented already on the web. You can google it and find more about it yourself!

Now Im gonna teach you how to create your own dll file and use it in your programs!  Some might have seen the FLAMES app that I coded in C#. It actually uses a dll file to store the class that does the computation work. And has the GUI stuff separately.

To create a dll, just create a .cs file that has the classes that must be stored in the dll. Say, we want a C# class to store and display some info about students in a class (school. not oops class. lol!). So we will create the following ‘class’ for that purpose.

using System;

namespace StudentDetailsClass
{
    public class Student
    {
        private string name;
        private int age;

        public Student (String name, int age)
        {
            this.name=name;
            this.age=age;
        }

        public  string Name
        {
            get
            {
                return name;
            }
        }

        public  int Age
        {
            get
            {
                return age;
            }
        }
    }
}

Now that we have created the class that we will store in our dll file, we need to compile it and unlike the usual compilation routine, we need to generate a .dll file rather than an executable. To do that you need to provide set some options in the cs compiler (csc.exe). Those who haven’t compiled c# programs before can read the next paragraph. Others can safely skip it.

Some may not have experience of compiling C# code from the command line. You may been using Visual Studio for that purpose. Compiling from command line is very simple. Fist you need to add csc.exe which is the “C Sharp Compiler” to your System Path variable. To do that Right Click My Computer and select Properties and in Properties select Advanced Tab in XP or Advanced system settings from side bar in case of Windows 7 or Vista and select “Environment Variables” Button in the ensuing dialog box. Now user variables list select the variable with the name “path” and select “edit”. Now you need to locate your csc.exe folder. Most probably it will be in “C:\Windows\Microsoft.NET\Framework\v4.0.30319” folder. If you use a different version of the .Net Framework then the last folder name may be different. Check whether csc.exe is in that folder. Now copy the path of the folder. Now in the edit the Path Environment variable and in the value field, add a semi colon “;” after whatever is present there by default and paste the path there and save it and close everything. You can also set the path directly by using,

set path = "C:\Windows\Microsoft.NET\Framework\v4.0.30319"

command on the command prompt. Then log off and log in again. Now open command prompt and type csc. You should get info about the version of .Net framework. This confirms that you have properly configured the path variable. Now, to compile a c# code file browse to its folder using command prompt and then use the command

csc   /out:MyApp.exe sourceName.cs

You need not specify the /out parameter. If you dont do that the output exe file will have same name as that of the source file name. This is how you compile a c# code file using the command line.

Alright. Now lets see how to compile a source file and generate a dll file unlike the exe file that we created above. To create a dll file (which is essentially a library file) you need to specify “library” as parameter for “/target” option. For example, to compile the above class stored as StudentDetailsClass.cs and generate “StudentDetails.dll” use following command.

csc /target:library /out:StudentDetailsClass.dll  StudentDetailsClass.cs

If you want to add mutliple cs files to the same dll, you can specify those cs files one after other as well. Now we have created our DLL file. Now we need to create a program that will implement this dll file. The DLL files that a program uses are called “references”. So we need to use “reference” option when compiling. We will come to that part later. Now  here is the code for the program which will use the class file.

using System;

// use the namespace of the dll
using StudentDetailsClass;

//Class with main method

namespace StudentDetails
{
    class StudentTest1
    {
        public static void Main(string[] args)
        {
            string name;
            int age;

            Console.WriteLine("Welcome To Students Details App!");

            Console.Write("Enter the number of students: ");
            int n = int.Parse(Console.ReadLine());

            //Student Class available in the dll file
            Student[] stu = new Student[n];

            Console.WriteLine("Enter details of the students...");
            for (int i = 0; i < n; i++)
            {
                Console.WriteLine("Student " + (i + 1) + ":");
                Console.Write("Enter Name and Age... :");
                name = Console.ReadLine();
                age = int.Parse(Console.ReadLine());
                stu[i] = new Student(name, age);
            }

            Console.WriteLine("Detials of the given students are: ");

            for (int i = 0; i < n; i++)
            {
                Console.WriteLine("Student " + (i + 1) + ":");
                Console.WriteLine("Name: "+stu[i].Name);
                Console.WriteLine("Age: " + stu[i].Age);
            }

            Console.WriteLine("\nThanks for using!");
            Console.Read();

        }
    }
}

Now save this file as something like “StudentDetailsApp.cs” and put it in the same folder as that of the dll file. Now to compile it use the following command.

csc  /reference:StudentDetailsClass.dll  StudentDetailsApp.cs

Now this should generate the exe file with the name StudentDetails.exe. Run it using the command,

StudentDetails.exe

Now you should get following output:

e:\C# Programming\Sandbox>csc /target:library /out:StudentDetailsClass.dll StudentDetailsClass.cs
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.

e:\C# Programming\Sandbox>csc /reference:StudentDetailsClass.dll StudentDetailsApp.cs
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.

e:\C# Programming\Sandbox>StudentDetailsApp.exe

Welcome To Students Details App!
Enter the number of students: 1
Enter details of the students...
Student 1:
Enter Name and Age... :Steve Robinson
20
Detials of the given students are:
Student 1:
Name: Steve Robinson
Age: 20

Thanks for using!

Running applications from the console is ok for small applications. But when you are building your project you may want to add multiple references or build complex classes with large number of such classes. In that case you should definitely use Visual Studio IDE. So Ill also tell you how to create and use dlls using Visual Studio.

While Creating the new project, select “Class Library” as the project type. Now create the classes that will come under the dll file and compile them. This will generate the dll file. Now create your main project which may be a Windows Forms app or a Console application. Now In the project explorer pane, right click the references folder and select “Add References” Now in the ensuing dialog box, select Browse tab and browse to the previously created dll file and add it. Now you can use the classes of the dll in your program.

I hope this simple tutorial might have cleared some confusion or ignorance about dll files. As always, if you have any doubts/clarifications/suggestions add a comment below!  And share the article on twitter/facebook/digg etc of you like it!

Steve Robinson.

15 thoughts on “[C#]Creating and using .dll files

    • It depends. Many and I mean MANY applications that we use depend on a lot of Dll files loaded in the Windows directory. And they also come with certain dlls that they only use. So this way the code is organized in a space efficient way! The best example would be the dx_d39.dll (? not sure with name). This dll is used for DirectX by many applications. They share this dll.

    • I dont get what you’re asking. In which file do u put a dll??? That doesnt make any sense. The dll file is an independent file. You refer the classes inside the dll file in your application. Any number of applications can refer the code inside the file.

  1. Thank you Very Much, this has become my Best material in creating and using DLL in c# topic. You made this very simple and reliable.
    Thanks Everyone for your precious post.

  2. great tutorial!. This sounds silly but can i create a .dll file out of a class which has main method declared? thanks!

    • Hi Manjiri. I am sorry but its been several years since Ive moved on from .Net and other Microsoft stuff. 🙂 So I am not in a good position to answer your query. It would be very helpful for you if you could go to places like stackoverflow.com and get your answers! Once again Im sorry.

Leave a reply to Đoan Nguyễn Thị Thái Cancel reply