📁 File Scoped Namespaces = Cleaner Code
Namespaces add indentation. File scoped namespaces are cleaner. Less nesting, more readable.
❌ Old Style
namespace MyApp
{
namespace Models
{
public class User { }
}
namespace Services
{
public class UserService { }
}
}
✅ File Scoped
namespace MyApp.Models;
public class User { }
namespace MyApp.Services;
public class UserService { }
📝 File Scoped Namespace Examples
// Before (C# 9 and earlier)
namespace MyApp.Models
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
}
// After (C# 10+)
namespace MyApp.Models;
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
// Multiple namespaces in one file
namespace MyApp.Models;
public class User { }
namespace MyApp.DTOs;
public class UserDto { }
// Nested with file scoped
namespace MyApp.Data.Entities;
public class User { }
// Global using directives
global using System;
global using System.Collections.Generic;
global using System.Linq;
global using System.Threading.Tasks;
// Usings with file scoped
using System.Text;
using Microsoft.Extensions.Logging;
namespace MyApp.Services;
public class MyService
{
private readonly ILogger _logger;
public MyService(ILogger logger)
{
_logger = logger;
}
}
✅ Benefits
- ✓ Less indentation
- ✓ More readable
- ✓ Reduces nesting
- ✓ Cleaner code
- ✓ Consistent with global usings
“File scoped namespaces reduce indentation. Cleaner, more readable. Essential for modern C#.”
