C# - File-scoped Namespaces
Keyur Ramoliya
Posted on December 1, 2023
C# 10.0 introduced the concept of file-scoped namespaces, allowing you to define a namespace for the entire file without needing additional indentation. This feature leads to less nesting and cleaner code, especially in large projects with many files.
Here's how you can use file-scoped namespaces:
Declare a File-scoped Namespace:
Instead of wrapping your classes, structs, and other types in a namespace block, you can declare a namespace that applies to the entire file. This is done using thenamespace
keyword followed by the namespace name and a semicolon.Reduce Nesting and Indentation:
Since the namespace declaration is file-scoped, there's no need for additional indentation for the entire file's contents.
Example:
Instead of:
namespace MyProject.Models
{
public class UserModel
{
// Model properties and methods here
}
public class ProductModel
{
// Model properties and methods here
}
}
You can write:
namespace MyProject.Models;
public class UserModel
{
// Model properties and methods here
}
public class ProductModel
{
// Model properties and methods here
}
By using file-scoped namespaces, your code becomes cleaner and more readable, reducing the amount of boilerplate and indentation required. This is especially helpful in projects with a deep directory structure and many files, making it easier to understand the file's scope at a glance.
Posted on December 1, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.