C# - File-scoped Namespaces

theramoliya

Keyur Ramoliya

Posted on December 1, 2023

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.

💖 💪 🙅 🚩
theramoliya
Keyur Ramoliya

Posted on December 1, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

C# - Struct Improvements in C# 10.0
csharp C# - Struct Improvements in C# 10.0

December 2, 2023

C# - File-scoped Namespaces
csharp C# - File-scoped Namespaces

December 1, 2023

C# - with expressions
csharp C# - with expressions

December 21, 2023