📁 Namespaces = Folders for Code
All classes in one file? Chaos. Namespaces organize code. Group related classes, avoid naming conflicts.
❌ Without Namespace
class User { }
class Product { }
class Order { }
// All global, easy conflicts
✅ With Namespace
namespace MyApp.Models {
class User { }
}
namespace MyApp.Services {
class UserService { }
}
🎯 Namespace Best Practices
// File-scoped namespace (C# 10)
namespace MyApp.Services;
public class UserService { }
// Nested namespaces
namespace MyApp.Data
{
namespace Models
{
public class User { }
}
}
// Using directive
using MyApp.Services;
var service = new UserService();
// Alias
using Project = MyApp.ProjectManagement.Models.Project;
// Using static
using static System.Math;
var result = Sqrt(25);
// Namespace aliasing
global using MyApp.Common;
💡 Common Structure
- MyApp.Models (data models)
- MyApp.Services (business logic)
- MyApp.Controllers (API controllers)
- MyApp.Data (database access)
- MyApp.Common (shared utilities)
“100 classes in one namespace, confusion. Organized with namespaces. Now code is clean, discoverable. Namespaces are essential for code organization.”
