C# File-Scoped Namespace — Complete Guide
In this tutorial, you'll learn about C# File. We cover key concepts, practical examples, and best practices.
Every C# file starts with a namespace block that indents the entire file. After four or five files, you have hundreds of wasted indentation levels. File-scoped namespaces eliminate the block and the extra indentation.
Wrong
namespace MyApp.Services
{
public class UserService
{
public void DoSomething()
{
// Indented twice before any code
}
}
}
Output: Works, but every type inside the namespace is indented an extra level. When the file is 200 lines, that is 200 unnecessary leading spaces.
Right
namespace MyApp.Services;
public class UserService
{
public void DoSomething()
{
// No unnecessary indentation
}
}
Output: Same compiled result. The ; after the namespace declaration tells the compiler every type in this file belongs to that namespace.
A file can only have one file-scoped namespace. If you need nested namespaces or multiple, use the traditional block syntax.
Prevention
- Use file-scoped namespaces in all new C# files — they are the standard in .NET 6+.
- Use a single namespace per file (which you should do anyway).
- Keep the namespace line at the top, after
usingdirectives. - Use traditional block namespace only when a file contains types in multiple namespaces (rare).
- Configure your editor to use file-scoped namespaces by default.
- Ensure your project targets .NET 6+ (or uses C# 10+).
Common Mistakes with file scoped namespace
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
File-scoped namespaces are the default in all DodaTech projects using .NET 6+. For more C# practices, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro