Sometimes it can be useful to share your code between projects or with other individuals. One easy way to do this is through the creation of a NuGet package.

Below are some steps you can take to publish your package to a GitHub NuGet feed, but the process should be similar for any other feed.

Create the Project

Before we can share something, we need to create the actual project / code. For this example, I'll use a simple class library with a single file:

namespace Nuget.Demo
    public class Helpers
        public int Add(int x, int y)
            return x + y;

        public int Mod(int x, int y)
            return x % y;

Update the Project File

Next, we need to add some properties to the csproj file of the project.

<Project Sdk="Microsoft.NET.Sdk">


	<!-- NuGet Properties -->
	<Copyright>Kevin Williams 2023</Copyright>
	<Authors>Kevin Williams</Authors>
	<Company>My Company</Company>
	<Description>A demo nuget package</Description>


Generate the package

Now, we can create a .nupkg by running the dotnet pack command.

dotnet pack --configuration Release
This could be referenced and used locally, if you don't want to publish to a particular feed

Publish the Package

If you wish to publish the package to a feed, we need to create a nuget.config file, which can be placed in the root of your project.

<?xml version="1.0" encoding="utf-8"?>
    <clear />
    <add key="github" value="" />
      <add key="Username" value="OWNER" />
      <add key="ClearTextPassword" value="TOKEN" />

Be sure to replace OWNER and TOKEN with your GitHub username and access token

To create an access token in GitHub, navigate to Settings -> Developer Settings -> Tokens (Classic)

Now that we have a config file, we can push to our GitHub feed with the following:

dotnet nuget push <PACKAGE>.nupkg --source "github"

Connect to your feed

The only thing left is to connect to the GitHub feed and utilize our new package in another project. This can be done by adding a new NuGet source within Visual Studio where GITHUB_USER is your GitHub username

Or from the command line

dotnet nuget add source --username USERNAME --password GITHUB_TOKEN --store-password-in-clear-text --name github ""

Utilize the Package

Now that we've added the source / feed, we can add the package to our new project

dotnet add <PACKAGE_NAME>
using Nuget.Demo;

var helper = new Helpers();
var sum = helper.Add(10, 20);
var remainder = helper.Mod(25, 3);