Sunday 8 May 2011

Creating DLL in C#

What is DLL?
A dynamic linking library (DLL) is linked to your program at run time. DLL is similar to an EXE but is not directly executable. Functions in the dll are called from the main exe. It provides a way to split what would be a very large exe into an exe plus one or more dlls.
Creating DLL in C#
To creating DLL in C# just follow next steps-
Goto File -> New Project then choose Class Library you will see window like below.
Here i am going to show DLL for addition, subtraction, multiplication, and division. Code for this is given below-

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

namespace ClassLibrary1
{
    public class Class1
    {
        public int add(int x,int y)
        {
           
          int  z = x + y;
          return z;
        }
        public int sub(int x, int y)
        {
           
          int   z = x - y;
          return z;
        }
        public int mul(int x, int y)
        {
            
            int z = x * y;
            return z;
        }
        public int div(int x, int y)
        {
            
            int z = x / y;
            return z;
        }
    }
}
After this Build this class by pressing F6 and dll will generate this class library now you can use this in any other application where you want to use this dll.
Using DLL in C# Application
For using DLL in application you have to make add reference of the dll that you

Design the form as shown in below picture -

 private void button1_Click(object sender, EventArgs e)
        {
           ClassLibrary1.Class1 c1 = new Class1();
          int result=  c1.add(int.Parse(textBox1.Text),int.Parse(textBox2.Text));
          textBox3.Text = result.ToString();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ClassLibrary1.Class1 c2 = new Class1();
            int result = c2.sub(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
            textBox3.Text = result.ToString();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            ClassLibrary1.Class1 c3 = new Class1();
            int result = c3.mul(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
            textBox3.Text = result.ToString();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            ClassLibrary1.Class1 c4 = new Class1();
            int result = c4.div(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
            textBox3.Text = result.ToString();
        }

No comments:

Post a Comment