147-c-sharp-how-to-make-a-dll-file

In order to make a dll file from C#, first step is to start creating class library .dll project (see figure bellow).

c-sharp-dll-project

Rest of the job is similar to writing down any other C# class, but we need to take care about what class members are public. It is useful to make public all of the members that we need to easily access later on when we want to use created .dll.

c_sharp_dll_01

Each public class in future namespace (dll file), suppose to be in the separated cs file as the part of the project.

c_sharp_dll_02

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MathLibrary
{

public class Addition

{

}

}

Inside public class Addition, public static function has to be added, for example Summing.

public static long Summing(long i, long j)
{

return (i + j);

}

Next thing to be done is to add new cs file to the project. New class Subtraction is not initially public. So we need to make it manually.

c_sharp_dll_03

 

public class Subtraction
{
}
Inside public class Subtraction, new public static function has to be added, let’s say Subtracting:

public static long Subtracting (long i, long j)
{

return (i – j);

}

So, overall code is:
So, overall code is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MathLibrary
{

public class Addition

{

public static long Summing(long i, long j)

{

return (i + j);

}

}

}

and

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MathLibrary
{

public class Subtraction

{

public static long Subtracting(long i, long j)

{

return (i – j);

}

}

}

Then we need to build solution by pressing F6 key.

c_sharp_dll_04

Now, we need to use dll made. We start new project and then copy dll into project folder. Then we need to add new reference in the project that uses dll:

c_sharp_dll_06

Choose reference:

c_sharp_dll_05

When we try to implement classes and methods defined in our dll file,

c_sharp_dll_08

c# compiler will not know called class. Now we can type new namespace
using MathLibrary;
and everything will work fine. Whole code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MathLibrary;

namespace UseDll
{

class Program
{

static void Main(string[] args)

{

long num1 = 12;

long num2 = 3;

long sum = Addition.Summing(num1, num2);

Console.WriteLine(“Sum is: ” + sum.ToString());

Console.ReadLine();

long product = MathLibrary.Subtraction.Subtracting(num1, num2);

Console.WriteLine(“Difference is: ” + product.ToString());

Console.ReadLine();

}

}

}

External links:

C# how to make dll file i.e. how to create class library on Microsoft

Posted in c-sharp-code-examples

Leave a Reply

Your email address will not be published. Required fields are marked *

*