Search⌘ K
AI Features

Building Class Libraries

Explore how to create reusable .NET class libraries to organize your C# code into deployable DLLs. Learn to define custom types, use namespaces, and understand members such as fields and methods. Gain practical skills to instantiate classes in separate projects, enabling code reuse across applications.

Class library assemblies group types into easily deployable units (DLL files). Apart from learning about unit testing, we have only created console applications or .NET Interactive notebooks to contain our code. To make the code we write reusable across multiple projects, we should put it in class library assemblies like Microsoft.

Creating a class library

The first task is to create a reusable .NET class library:

Step 1: Use your preferred coding tool to create a new project, as defined in the following list:

  • Project template: Class Library or classlib

  • Project file and folder: PacktLibraryNetStandard2

  • Workspace/solution file and folder: Chapter05

Step 2: Open the PacktLibraryNetStandard2.csproj file, and note that, by default, class libraries created by the .NET SDK 7 target .NET 7 and, therefore, can only be referenced by other .NET 7-compatible assemblies, as shown in the following markup:

C#
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>

Step 3: Modify the framework to target .NET Standard 2.0, add an entry to explicitly use the C# 11 compiler, and statically import the System.Console class to all C# files, as shown highlighted in the following markup:

C#
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>11</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Using Include="System.Console" Static="true" />
</ItemGroup>
</Project>

Step 4: Save and close the file.

...