C# Creating a Class Library

This instruction post is an abbreviation of Microsoft tutorial found HERE.

Contents

  • Create the Library
  • Using the Library
  • Unit Testing
  • Including the .dss Directly
  • Setup

    Create an SLN (project solution file)

    An SLN is a Visual Studio solution file that keeps information about the organization of projects in a file.

    dotnet new sln

    Create the class library project

    The -o (–output) flag specifies the directory to place the project. It will create the directory.

    dotnet new classlib -o StringLibrary

    Add the project to the solution

    dotnet sln add StringLibrary/StringLibrary.csproj

    Add code to the library

    Add the following code to the StringLibrary/Class1.cs file

    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);
        }
    }

    Build the solution

    dotnet build

    Using the Library

    Create a console app

    dotnet new console -o ShowCase

    Add the console app to the solution

    dotnet sln add ShowCase/ShowCase.csproj

    Modify the ShowCase/Program.cs file

    using UtilityLibraries;
    
    class Program {
        static void Main(string[] args) {
            foreach(string s in args){
                var uc = s.StartsWithUpper();
                Console.WriteLine($"String {s} starts with uppser case {uc}");
            }
        }
    }

    Add a ‘StringLibrary’ reference to ‘ShowCase’

    dotnet add ShowCase/ShowCase.csproj reference StringLibrary/StringLibrary.csproj

    Run ‘ShowCase’

    dotnet run --project ShowCase/ShowCase.csproj AB ab

    Unit Testing

    Create the unit test project and add a reference

    dotnet new mstest -o StringLibraryTest
    dotnet add StringLibraryTest/StringLibraryTest.csproj reference StringLibrary/StringLibrary.csproj

    Run the unit test

    dotnet test StringLibraryTest/StringLibraryTest.csproj

    Including the .dll directly

    Add the following to your project’s .csproj file. Change the StringLibrary project name as necessary.

      <ItemGroup>
        <Reference Include="StringLibrary">
          <HintPath>./lib/StringLibrary.dll</HintPath>
        </Reference>
      </ItemGroup>