28.8.08

Creating Assembly in VS C#.NET

Create an Empty Class Library Project
Select File->New->Project->Visual C# Projects->Class Library. Select your project name and appropriate directory using Browse button and click OK. See Figure 1.




















Figure 1.
Project and Its files
The Solution Explorer adds two C# classes to your project. First is AssemblyInfo.cs and second is Class1.cs. We don't care about AssemblyInfo. We will be concentrating on Class1.cs. See Figure 2.



























Figure 2
The mcMath Namespace
When you double click on Class1.cs, you see a namespace mcMath. We will be referencing this namespace in our clients to access this class library.
using System;


namespace mcMath
{
///
/// Summary description for Class1.
///

public class Class1
{
public Class1()
{
// // TODO: Add constructor logic here //
}
}
}
Now build this project to make sure every thing is going OK. After building this project, you will see mcMath.dll in your project's bin/debug directory.
Adding Methods
Open ClassView from your View menu. Right now it displays only Class1 with no methods and properties. Lets add one method and one property. See Figure 3.
















Figure 3.
Build the DLL
Now build the DLL and see bin\debug directory of your project. You will see your DLL. Piece of cake? Huh? :).
Building a Client Application
Calling methods and properties of a DLL from a C# client is also an easy task. Just follow these few simple steps and see how easy is to create and use a DLL in C#.
By adding the Dll to the reference of the project to get all the features
Call mcMath Namespace, Create Object of mcMathComp and call its methods and properties.
You are only one step away to call methods and properties of your component. You follow these steps:
  1. Use namespace
    Add using mcMath in the beginning for your project. using mcMath;
  2. Create an Object of mcMathComp. mcMathComp cls = new mcMathComp();
  3. Call Methods and Properties

Now you can call the mcMathComp class method and properties as you can see I call Add method and return result in lRes and print out result on the console.
mcMathComp cls = new mcMathComp();
long lRes = cls.Add( 23, 40 );
cls.Extra = false;

Console.WriteLine(lRes.ToString());

Entire Project

using System;
using mcMath;
namespace mcClient
{
///


/// Summary description for Class1.
///

class Class1
{
///
/// The main entry point for the application.
///

[STAThread]
static void Main(string[] args)
{
mcMathComp cls = new mcMathComp();
long lRes = cls.Add( 23, 40 );
cls.Extra = false;
Console.WriteLine(lRes.ToString());
}
}
}

No comments: