Course contentsShow
← C#
Lesson 88 of 1,9081. C# Language FoundationsFree lesson

File-Scoped Namespaces

Implement cleaner file structures by eliminating unnecessary indentation.

Simplifying Your Code with File-Scoped Namespaces

In this lesson, you will learn how to reduce visual noise in your C# files by using file-scoped namespaces to eliminate unnecessary indentation.

The Problem: The "Nested" Look

In older C# versions, whenever you defined a namespace, you had to wrap all your classes and structures inside a set of curly braces { }. Because your code was inside those braces, you had to indent everything by one level. Over time, as files grew, that extra level of indentation made the code feel cramped and harder to read.

The Solution: File-Scoped Namespaces

C# introduced a cleaner way to handle this. Instead of using curly braces to define a scope, you can use a single line at the top of your file. This tells the compiler that everything in this file belongs to that namespace, without forcing you to indent the entire document.

Traditional Namespace Syntax:

namespace MyApp.Utilities 
{
    public class Processor 
    {
        // Everything here is indented, 
        // pushing code further to the right.
    }
}

File-Scoped Namespace Syntax:

namespace MyApp.Utilities;

public class Processor 
{
    // No extra indentation needed!
    // This looks much cleaner.
}

Why it Matters

By removing the extra braces and the resulting indentation, your code becomes easier to scan. It reduces the "visual tax" on your eyes, especially when you are working on large projects where you have dozens of files. Since you already know about Global Using Directives and Top-Level Statements, you can see how C# is evolving to make your source files as lean and focused as possible. You simply declare the namespace once at the top with a semicolon, and you are done for the entire file.

Key Takeaway: File-scoped namespaces allow you to define a file's namespace with a single semicolon, removing unnecessary braces and indentation to keep your code clean and readable.