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
-
Right-click on your project β Manage NuGet Packages
-
Browse for the desired package (e.g.,
Newtonsoft.Json
) -
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
-
Always use specific versions for production projects
-
Keep dependencies minimal to reduce bloat
-
Regularly update packages to benefit from fixes and features
-
Restore packages on a new machine using:
dotnet restore
- Ensures all dependencies are downloaded
π 8. Summary Table
Feature | Description |
---|---|
NuGet | Package manager for .NET |
Install package | dotnet add package <PackageName> |
Update package | dotnet add package <PackageName> --version x.x.x |
Remove package | dotnet remove package <PackageName> |
Project reference | <PackageReference> in .csproj |
Usage | Import 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.