How to create a library in C#

To create a library in C#, you need to perform following steps:

Step 1: Create a new C# project in visual studio. After the project is created, add a new class in the project with the following code:

Class Name and File Name: MathLib.cs

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

namespace ConsoleApplication6
{
    public class MathLib
    {
        public int Add(int x, int y)
        {
            return x + y;
        }
    }
}

Step 2: In your main function (located in Program class), write the following code:

static void Main(string[] args)
{
    MathLib mathObj = new MathLib();
    Console.WriteLine(mathObj.Add(7, 8));
}

Step 3: Open the Visual Studio Native Tools Command Prompt from

Start Menu -> Program Files -> Visual Studio

Write the following command in native tools command prompt

Note: First you need to browse into directory where MathLib.cs is located. Use dos commands to navigate to directory

csc /t:library MathLib.cs

The above command will generate a MathLib.dll file

Step 4: Now you can use the following command to compile the Program.cs (file containing Main function) with the newly created library:

csc Program.cs /r:MathLib.dll

The above line will create Program.exe file that you can run and see that it will be using the function call of the function we defined in library

Step 5: Next time instead of using command prompt commands again and again you can add a permanent reference to library, so that program is compiled directly from visual studio:

Click on solution explorer, Right click on References and click on Add Reference. From browse, select the path of MathLib.dll we just created. It will be permanently included in the project for future use.

Tags:,

Add a Comment

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

Spam Protection by WP-SpamFree