Packages & Imports (Namespaces & NuGet) in C#
Organise code with namespaces, using directives, global using (C# 10+), file-scoped namespaces, and manage third-party packages with NuGet.
What is a Namespace?
Declaring a Namespace
A namespace groups related classes, structs, and interfaces. It prevents name collisions across large codebases. The namespace keyword wraps type declarations.
Nested Namespaces
Namespaces can be nested to reflect project structure. The dot notation `MyApp.Data.Repositories` is shorthand for nesting.
Using Directives
Basic using Directive
The `using` directive at the top of a file brings all public types from a namespace into scope for that file.
Namespace & Type Aliases
Use `using Alias = FullNamespace.TypeName` to shorten long names or resolve ambiguity when two namespaces contain a type with the same name.
Static Using
`using static ClassName` imports all static members of a class directly into scope, so you can call them without the class prefix.
Global Using (C# 10+)
global using Directive
Prefixing `using` with `global` makes a namespace available to every file in the project. Introduced in C# 10 (.NET 6+).
Implicit Usings (.NET 6+)
When `<ImplicitUsings>enable</ImplicitUsings>` is set in the .csproj, the SDK automatically adds global usings for the most common namespaces based on the project type.
File-Scoped Namespaces (C# 10+)
File-Scoped Namespace Syntax
Instead of wrapping the entire file in a `namespace { }` block, declare the namespace with a semicolon. The entire file belongs to that namespace.
Fully Qualified Names
Using Fully Qualified Names
When two imported namespaces contain a class with the same name, the compiler reports an ambiguity error. Use the fully qualified name to resolve it without an alias.
The System Namespace
Core Types in System
`System` contains fundamental types: `Console`, `Math`, `String`, `Int32`, `Boolean`, `DateTime`, `Exception`, `Object`, and more. It is the C# equivalent of Java's `java.lang`.
Commonly Used .NET Namespaces
Beyond `System`, several namespaces are used in almost every C# project. Knowing them saves time looking things up.
NuGet — Package Manager
Adding a NuGet Package
Use the `dotnet add package` CLI command to add a NuGet package. The package reference is saved in the `.csproj` file and the code is downloaded to a local cache.
Package Reference in .csproj
The `.csproj` file is the project manifest — it lists target framework, nullable settings, implicit usings, and all NuGet package references.