C# Tutorial: Namespaces and Modules
Namespaces, using directives, file-scoped namespaces, access modifiers, and NuGet packages in C#.
Namespaces
Namespaces prevent name collisions and organize code logically:
```csharp
namespace MyApp.Models {
public class User {
public string Name { get; set; } = "";
}
}
namespace MyApp.Services {
using MyApp.Models; // bring User into scope
public class UserService {
public User Create(string name) => new User { Name = name };
}
}
```
---
File-Scoped Namespaces (C# 10+)
Removes one level of indentation — the namespace applies to the whole file:
```csharp
namespace MyApp.Models; // no braces needed
public class Product {
public string Name { get; set; } = "";
}
```
---
using Directives
```csharp
using System; // namespace import
using System.Collections.Generic;
using static System.Math; // import static members
using Alias = System.DateTime; // alias
double r = Sqrt(16); // from static import
Alias now = Alias.Now;
```
---
Global Usings (C# 10+)
Add to a single file (e.g., `GlobalUsings.cs`) and they apply project-wide:
```csharp
global using System;
global using System.Collections.Generic;
global using System.Linq;
```
---
Partial Classes
Split a class across multiple files — common in auto-generated code:
```csharp
// File1.cs
partial class Customer {
public string Name { get; set; } = "";
}
// File2.cs
partial class Customer {
public void Greet() => Console.WriteLine($"Hi, {Name}");
}
```
---
NuGet Packages
C#'s package manager. Install via CLI:
```bash
dotnet add package Newtonsoft.Json
dotnet add package Dapper
```
Or in `.csproj`:
```xml
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
```
---
What's Next?
Your code is well-organized. Next: **concurrency** — async/await, Task, and parallel programming.
What you'll learn in this C# namespaces and modules tutorial
This interactive C# tutorial has 5 hands-on exercises. Estimated time: 10 minutes.
- Namespaces — A class is in namespace `MyApp.Models`. Use a `using` directive to bring it into scope and print `user.Name` where `Name…
- static using — Use `using static System.Math` to import `Math` methods statically, then call `Sqrt(16)` without the `Math.` prefix and …
- using Alias — Create an alias `using Env = System.Environment`. Use `Env.NewLine` ... actually, use `using Now = System.DateTime` and …
- Partial Class — Two `partial class Customer` definitions combine into one. The result should print `"Hi, Alice"` when `Greet()` is calle…
- Nested Namespaces — Define `namespace Company.HR` with a `Employee` class. In `Main`, create `Employee { Name = "Bob" }` and print the name.
C# Namespaces and Modules concepts covered
- Namespaces
- File-Scoped Namespaces (C# 10+)
- using Directives
- Global Usings (C# 10+)
- Partial Classes
- NuGet Packages
- What's Next?