Creating a Class Library

Learn to create a class library using Visual Studio

We'll cover the following...

Class library projects don’t need to contain the Main method, because a library isn’t an executable. It can’t run but can be used inside other projects.

Let’s create and use a class library in Visual Studio.

First, create a console application that serves as an executable. After creation, we have a window similar to the following:

Console application template
Console application template

Right-click the “Solution” node in the “Solution Explorer” and click “Add” -> “New Project.”

Adding a new project
Adding a new project

Set “Class library” as the project type and finish the project creation.

Our solution now contains two projects.

Solution Explorer
Solution Explorer

Let’s create an Employee class with the following contents:

using System;

namespace EmployeeDirectory
{
    public class Employee
    {
        public string firstName;
        public string lastName;

        public Employee(string firstName, string lastName)
        {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public void PrintFullName()
        {
            Console.WriteLine($"{firstName} {lastName}");
        }
    }
}

Now, in order to use our new class library, we must reference it from the place where we want to use it.

Right-click the “Dependencies” node inside the console project and click “Add Project Reference.”

From the list, check the class library project and click “OK”:

Adding a reference
Adding a reference

With the using directive, we now can import the namespaces that reside in the class library project and start using the classes from there.

using EmployeeDirectory;

namespace MyFirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee employee = new Employee("John", "Doe");
            employee.PrintFullName();
        }
    }
}