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.

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay