0
0
CsharpConceptBeginner · 3 min read

File Scoped Namespace in C#: What It Is and How to Use

A file scoped namespace in C# is a way to declare a namespace that applies to the entire file without extra indentation or braces. It simplifies code by removing the need for wrapping all code inside curly braces, making files cleaner and easier to read.
⚙️

How It Works

Imagine you have a box labeled with a name, and everything inside that box belongs to that label. In traditional C# namespaces, you open the box with curly braces { } and put your code inside. This means you have to indent all your code to show it belongs inside the box.

A file scoped namespace changes this by labeling the entire file with a namespace without opening a box. This means you write namespace Name; at the top, and everything in that file automatically belongs to that namespace without extra indentation or braces.

This makes your code look cleaner and reduces the visual clutter of braces, especially in files with many lines of code.

💻

Example

This example shows a file scoped namespace declaration. Notice there are no braces and no extra indentation for the code inside the namespace.

csharp
namespace MyApp.Utilities;

public class Helper
{
    public static void Greet()
    {
        System.Console.WriteLine("Hello from file scoped namespace!");
    }
}

class Program
{
    static void Main()
    {
        Helper.Greet();
    }
}
Output
Hello from file scoped namespace!
🎯

When to Use

Use file scoped namespaces when you want to write cleaner and more readable code files without extra indentation. They are especially helpful in files with many classes or methods where traditional braces add visual noise.

Real-world use cases include modern C# projects where simplicity and clarity are important, such as libraries, APIs, or any codebase aiming for a neat structure. It also helps when working with tools or editors that benefit from less nested code.

Key Points

  • File scoped namespaces remove the need for curly braces around the namespace.
  • They apply the namespace to the entire file automatically.
  • They reduce indentation and improve code readability.
  • Introduced in C# 10, requiring .NET 6 or later.
  • They are fully compatible with traditional namespaces in the same project.

Key Takeaways

File scoped namespaces simplify code by removing braces and indentation for namespaces.
They apply the namespace to the whole file automatically.
Use them to make your C# files cleaner and easier to read.
They require C# 10 or later and .NET 6 or newer.
They work alongside traditional namespace declarations without issues.