DEV Community

Cover image for C# - File-scoped Namespaces
Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - File-scoped Namespaces

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:

  1. 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 the namespace keyword followed by the namespace name and a semicolon.

  2. 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
    }
}
Enter fullscreen mode Exit fullscreen mode

You can write:

namespace MyProject.Models;

public class UserModel
{
    // Model properties and methods here
}

public class ProductModel
{
    // Model properties and methods here
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)