Monday, July 14, 2014

Creating C# Class Library (DLL) Using Visual Studio .NET

Step 1:- File->New->Project->Visual C# Projects->Class Library. Select your project name and appropriate directory click OK
After Clicking on button ‘OK’, solution explorer adds one C# class ‘Class1.cs’. In this class we can write our code.


When we double click on Class1.cs, we see a namespace CreatingDLL. We will be use this namespace in our project to access this class library.

Step 2:- Within Class1.cs we create a method named ‘sum’ that takes two integers value and return sum to witch method passed numbers.
using System;
namespace CreatingDLL
{
    public class Class1
    {
        /// <summary>
        /// sum is method that take two integer value and return that sum
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public int sum(int x, int y)
        {
            return x + y;
        }
     }
}

Step 3:- Now build the Application and see bin\debug directory of our project. ‘CreatingDLL.dll’ is created.
Now we create another application and take this DLL (CreatingDLL.dll) reference for accessing DLL’s method.

Steps for accessing created DLL
Step 4:- File->New->Project->Visual C# Projects->Windows Form Application.
Step 5:- Designed windows form as bellow figure.
Step 6:- Add reference of DLL (CreatingDLL) which we created before few minutes.
After adding reference of DLL, following windows will appear.

Step 7:- Write code on button click of Windows Form Application. Before creating object and making method of Add DLL, add namespace CreatedDLLin project as bellow code.
using System;
using System.Windows.Forms;
using CreatingDLL;
namespace AccessingDLL
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            Class1 c1 = new Class1();
            try
            {
                txtResult.Text =Convert.ToString(c1.sum(Convert.ToInt32(txtNumber1.Text),Convert.ToInt32(txtNumber2.Text)));
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

}

Step 8:- Now build the application and execute project and see output.