Building Class Libraries
Learn about creating reusable class library assemblies, defining classes, understanding members, and instantiating classes in a console application.
We'll cover the following...
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:
<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:
<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.
Step 5: Delete the file named Class1.cs
. ...