C# Class Library Projects Introduction


This entry is part 1 of 2 in the series C# Class Library

A project that contains only classes (and other type definitions if necessary) but no entry point is called a class library. When developing C# applications in Visual Studio you can place classes in separate files in your projects. You can also place your classes in completely separate projects.

Class library projects compile into .dll assemblies and you can access their content by adding references to them from other projects, which might be part of the same solution but does not have to be. This extends the encapsulation that objects provide because class libraries can revised and updated without touching the projects that use them. You can upgrade services that applications provide without upgrading each and every application directly.

When an application uses classes defined in an external library, you can call that application a client application of the library. Code that uses a class that you define is often called client code.

Class Library Creation

Create a new project of type Class Library, name it ClassLib and save it in a folder. Rename the file Class1.cs to something more descriptive such as MyExternalClass.cs. To do this right-click on the file in the Solution Explorer window and select Rename. Click Yes on the dialog box. Add a new class to the project using the filename MYInternalClass.cs or something similar to whatever you named Class1.cs to. Modify the code to make the class MyInternalClass explicitly internal.

internal class MyInternalClass
{
}

Compile the project by selecting Build -> Build Solution.

Client Application

Create a new console application. Select Project -> Add Reference. You can also select the same option after right-clicking References in the Solution Explorer. Click the Browse tab and navigate to you library. Where is it? Locate the bin directory of your class library and click Debug and locate your .dll file. When the operation completes confirm that a reference was added in the Solution Explorer. Open the Object Browser window and examine the new reference to see what objects it contains. Modify the code in your client application to include a using statement: using ClassLib;

In the client application you can instantiate your library class.

Series NavigationC# Class Library Projects Part 2 >>