How to Create a Class Library in .NET Core
A class library is a project that contains reusable code such as functions, methods, and classes that can be shared across multiple applications. Class libraries encapsulate logic, making your codebase modular, maintainable and easier to test. In this article, we will explore how to create class library in .NET core application. After reading this article, you will be able to create class library easily.
Why should we use a Class Library
- Code Reusability: Code Reusability: You can share the same logic across different projects without rewriting code
- Maintainability: Changing in library will automatically reflect in all dependent projects
- Separation of Concerns: It allows you to keep your application components organized.
Prerequisites
Before you start, ensure you have the following:
- .NET SDK installed Download here
- Visual Studio OR Visual Studio Code
- Basic knowledge of C# and .NET Core
Method 1 : Using the .NET CLI
Step 1: Create the Class Library Project
- Open a terminal or command prompt
- Navigate to the directory/folder where you want to create the project.
- Run the following command to create a new class library
dotnet new classlib -n <LibraryName>
This will generate a project folder named <LibraryName> with necessary files including: <LibraryName>.csproj (project file) and a default class file (Class1.cs).
Step 2: Navigate into the Project Directory
cd <LibraryName>
Step 3: Build the Class Library
dotnet build
This command compiles the project and generates a .dll file in the bin directory. The .dll file is the compiled library that you can reference in other projects
Step 4: Reference the Class Library in Another Project
- Navigate to the directory of the project/application that will use this library
- Add the reference of class library
dotnet add reference ../<LibraryName>/<LibraryName>.csproj
- Run the build command in the main project directory to ensure the reference is correctly added
dotnet build
Method 2: Using Visual Studio
Create a New Class Library Project
- Open Visual Studio
- Click on "Create a new project"
- Select "Class Library" and click Next.
- Provide a name for your class library and click Create.