Let’s go through using NuGet packages in C# β€” the standard way to add external libraries and dependencies to your project.


πŸ“Œ 1. What is NuGet?

  • NuGet is the package manager for .NET.

  • It allows you to install, update, and manage external libraries in your projects.

  • Packages can include DLLs, tools, scripts, or content files.


πŸ“Œ 2. Finding and Installing Packages

Using Visual Studio

  1. Right-click on your project β†’ Manage NuGet Packages

  2. Browse for the desired package (e.g., Newtonsoft.Json)

  3. Click Install β†’ NuGet automatically adds it to your project

Using .NET CLI

dotnet add package Newtonsoft.Json
  • Installs the package and updates your project file automatically

πŸ“Œ 3. Using Installed Packages

After installing, import the namespace in your code:

using Newtonsoft.Json;
 
var person = new { Name = "Alice", Age = 25 };
string json = JsonConvert.SerializeObject(person);
Console.WriteLine(json);
  • The package is now ready to use in your project

πŸ“Œ 4. Updating Packages

Visual Studio

  • Go to Manage NuGet Packages β†’ Updates

  • Select package β†’ Update

.NET CLI

dotnet add package Newtonsoft.Json --version 14.0.1
dotnet restore
  • Ensures you’re using the latest or specific version

πŸ“Œ 5. Removing Packages

Visual Studio

  • Manage NuGet Packages β†’ Installed β†’ Uninstall

.NET CLI

dotnet remove package Newtonsoft.Json
  • Cleans up your project dependencies

πŸ“Œ 6. NuGet Package Configuration

  • Packages are tracked in your .csproj file:
<ItemGroup>
  <PackageReference Include="Newtonsoft.Json" Version="14.0.1" />
</ItemGroup>
  • Ensures reproducible builds across machines

πŸ“Œ 7. Best Practices

  1. Always use specific versions for production projects

  2. Keep dependencies minimal to reduce bloat

  3. Regularly update packages to benefit from fixes and features

  4. Restore packages on a new machine using:

dotnet restore
  • Ensures all dependencies are downloaded

πŸ“Œ 8. Summary Table

FeatureDescription
NuGetPackage manager for .NET
Install packagedotnet add package <PackageName>
Update packagedotnet add package <PackageName> --version x.x.x
Remove packagedotnet remove package <PackageName>
Project reference<PackageReference> in .csproj
UsageImport namespace with using

βœ… Tip:

  • Think of NuGet as npm for C# β€” it simplifies adding libraries without manually downloading DLLs.

  • Always check license compatibility when adding external packages.