Consuming .NET Assemblies


Consuming .NET Assemblies in C# program

As a good design practice you must divide large applications into multiple components so that it is easy to maintain the application code. It also helps in sharing your assemblies between different applications in the enterprise. For example, common utility classes used across multiple applications should be designed as a separate assembly.

In this article we will explain how to consume an existing assembly written in .NET from a C# program.

The first step is to add the assembly as a reference to the program, it is explained in detail in the article Adding Assembly as a Reference using Visual Studio.

Once the target assembly is added as reference to the project, next step is to import the namespace to the code file by using the using statement as explained in the article Namespaces. After importing the namespace, the types in the namespace can be used without qualifying.

Let’s explain the process using a Sample.

Open visual studio and create a new empty project named Utility. In the below screen Blank Solution project template is selected, it’s an empty solution project to which you can add any project.

Creating a New Visual Studio Blank Solution

Now, let’s add a class library project UtilsLib to this blank solution.

Adding Class Library Project to Blank Solution

 

The file structure in the solution explorer is shown in the below screen. The solution name is Utility and the class library name is UtilsLib.

Solution explorer file structure after adding class library project.

 

Now, let’s delete the Class1.cs from the library project. Add a new class named MathUtil.cs. Type the code shown in the below screen and compile the UtilsLib project. The output of the compilation is UtilsLib.dll which is stored in the bin/Debug directory of the project folder.

MathUtil class code.

Now let’s create a new console application project named ConsumerApp.

Create new console application project.

Add reference to the UtilsLib.dll as shown below. Please read the article Adding Assembly as a Reference using Visual Studio for details.

Adding reference to UtilsLib using Reference Manager

Once the assembly is added as reference you can import the namespace as shown below.

Using UtilsLib; statement imports the namespace to the code file. You have to do this in each code file which needs to use MathUtil class.

Importing UtilsLib

Type the code shown below in Program.cs file, compile and run the application.

Using MathUtil functions in Program file.

You should see the below output screen.

Output screen after compiling and executing the Console Application.