This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
In this tutorial, you create a simple class library that contains a single string-handling method.
Aclass library defines types and methods that are called by an application. If the library targets .NET Standard 2.0, it can be called by any .NET implementation (including .NET Framework) that supports .NET Standard 2.0. If the library targets .NET 8, it can be called by any application that targets .NET 8. This tutorial shows how to target .NET 8.
When you create a class library, you can distribute it as a NuGet package or as a component bundled with the application that uses it.
Visual Studio 2022 with the.NET desktop development workload installed. The .NET 8 SDK is automatically installed when you select this workload.
For more information, seeInstall the .NET SDK with Visual Studio.
Start by creating a blank solution to put the class library project in. A Visual Studio solution serves as a container for one or more projects. You'll add additional, related projects to the same solution.
To create the blank solution:
Start Visual Studio.
On the start window, chooseCreate a new project.
On theCreate a new project page, entersolution in the search box. Choose theBlank Solution template, and then chooseNext.
On theConfigure your new project page, enterClassLibraryProjects in theSolution name box. Then chooseCreate.
Add a new .NET class library project named "StringLibrary" to the solution.
Right-click on the solution inSolution Explorer and selectAdd >New Project.
On theAdd a new project page, enterlibrary in the search box. ChooseC# orVisual Basic from the Language list, and then chooseAll platforms from the Platform list. Choose theClass Library template, and then chooseNext.
On theConfigure your new project page, enterStringLibrary in theProject name box, and then chooseNext.
On theAdditional information page, select.NET 8, and then chooseCreate.
Check to make sure that the library targets the correct version of .NET. Right-click on the library project inSolution Explorer, and then selectProperties. TheTarget Framework text box shows that the project targets .NET 8.0.
If you're using Visual Basic, clear the text in theRoot namespace text box.
For each project, Visual Basic automatically creates a namespace that corresponds to the project name. In this tutorial, you define a top-level namespace by using thenamespace
keyword in the code file.
Replace the code in the code window forClass1.cs orClass1.vb with the following code, and save the file. If the language you want to use isn't shown, change the language selector at the top of the page.
using System;namespace UtilityLibraries{ public static class StringLibrary { public static bool StartsWithUpper(this string str) { if (string.IsNullOrWhiteSpace(str)) return false; char ch = str[0]; return char.IsUpper(ch); } }}
Imports System.Runtime.CompilerServicesNamespace UtilityLibraries Public Module StringLibrary <Extension> Public Function StartsWithUpper(str As String) As Boolean If String.IsNullOrWhiteSpace(str) Then Return False End If Dim ch As Char = str(0) Return Char.IsUpper(ch) End Function End ModuleEnd Namespace
The class library,UtilityLibraries.StringLibrary
, contains a method namedStartsWithUpper
. This method returns aBoolean value that indicates whether the current string instance begins with an uppercase character. The Unicode standard distinguishes uppercase characters from lowercase characters. TheChar.IsUpper(Char) method returnstrue
if a character is uppercase.
StartsWithUpper
is implemented as anextension method so that you can call it as if it were a member of theString class. The question mark (?
) afterstring
in the C# code indicates that the string may be null.
On the menu bar, selectBuild >Build Solution or pressCtrl+Shift+B to verify that the project compiles without error.
Add a console application that uses the class library. The app will prompt the user to enter a string and report whether the string begins with an uppercase character.
Add a new .NET console application named "ShowCase" to the solution.
Right-click on the solution inSolution Explorer and selectAdd >New project.
On theAdd a new project page, enterconsole in the search box. ChooseC# orVisual Basic from the Language list, and then chooseAll platforms from the Platform list.
Choose theConsole Application template, and then chooseNext.
On theConfigure your new project page, enterShowCase in theProject name box. Then chooseNext.
On theAdditional information page, select.NET 8 in theFramework box. Then chooseCreate.
In the code window for theProgram.cs orProgram.vb file, replace all of the code with the following code.
using System;using UtilityLibraries;class Program{ static void Main(string[] args) { int row = 0; do { if (row == 0 || row >= 25) ResetConsole(); string? input = Console.ReadLine(); if (string.IsNullOrEmpty(input)) break; Console.WriteLine($"Input: {input} {"Begins with uppercase? ",30}: " + $"{(input.StartsWithUpper() ? "Yes" : "No")}{Environment.NewLine}"); row += 3; } while (true); return; // Declare a ResetConsole local method void ResetConsole() { if (row > 0) { Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } Console.Clear(); Console.WriteLine($"{Environment.NewLine}Press <Enter> only to exit; otherwise, enter a string and press <Enter>:{Environment.NewLine}"); row = 3; } }}
Imports UtilityLibrariesModule Program Dim row As Integer = 0 Sub Main() Do If row = 0 OrElse row >= 25 Then ResetConsole() Dim input As String = Console.ReadLine() If String.IsNullOrEmpty(input) Then Return Console.WriteLine($"Input: {input} {"Begins with uppercase? ",30}: " + $"{If(input.StartsWithUpper(), "Yes", "No")} {Environment.NewLine}") row += 3 Loop While True End Sub Private Sub ResetConsole() If row > 0 Then Console.WriteLine("Press any key to continue...") Console.ReadKey() End If Console.Clear() Console.WriteLine($"{Environment.NewLine}Press <Enter> only to exit; otherwise, enter a string and press <Enter>:{Environment.NewLine}") row = 3 End SubEnd Module
The code uses therow
variable to maintain a count of the number of rows of data written to the console window. Whenever it's greater than or equal to 25, the code clears the console window and displays a message to the user.
The program prompts the user to enter a string. It indicates whether the string starts with an uppercase character. If the user presses theEnter key without entering a string, the application ends, and the console window closes.
Initially, the new console app project doesn't have access to the class library. To allow it to call methods in the class library, create a project reference to the class library project.
InSolution Explorer, right-click theShowCase
project'sDependencies node, and selectAdd Project Reference.
In theReference Manager dialog, select theStringLibrary project, and selectOK.
InSolution Explorer, right-click theShowCase project and selectSet as StartUp Project in the context menu.
PressCtrl+F5 to compile and run the program without debugging.
Try out the program by entering strings and pressingEnter, then pressEnter to exit.
In this tutorial, you created a class library. In the next tutorial, you learn how to unit test the class library.
Or you can skip automated unit testing and learn how to share the library by creating a NuGet package:
Or learn how to publish a console app. If you publish the console app from the solution you created in this tutorial, the class library goes with it as a.dll file.
Was this page helpful?
Was this page helpful?