Namespaces
Namespaces
Section titled βNamespacesβWhat it means
Section titled βWhat it meansβA namespace groups related types together and prevents naming collisions β two classes named Logger can coexist peacefully as long as they live in different namespaces (MyApp.Logging.Logger vs ThirdParty.Diagnostics.Logger). You bring a namespaceβs types into scope with a using directive so you donβt have to write the fully-qualified name every time.
Examples
Section titled βExamplesβnamespace MyApp.Models{ public class User { public string Name; }}
namespace MyApp.Services{ using MyApp.Models; // brings User into scope without full qualification
public class UserService { public User CreateUser(string name) => new User { Name = name }; }}
// File-scoped namespace (C# 10+) -- less indentation, one namespace per filenamespace MyApp.Utilities;
public class Helper { }
// Fully-qualified name, used when two namespaces have a colliding type namevar user = new MyApp.Models.User();Common mistake
Section titled βCommon mistakeβNaming a class the same as a commonly-used framework type (like List, Timer, or Task) without realizing it, then getting confusing compiler errors or accidentally shadowing the real type when both namespaces are using-imported.
namespace MyApp.Models{ public class Task { } // collides in name with System.Threading.Tasks.Task}
using System.Threading.Tasks;using MyApp.Models;
Task t = new Task(); // Error: 'Task' is an ambiguous reference between // 'System.Threading.Tasks.Task' and 'MyApp.Models.Task'
// Fix: fully qualify one of themMyApp.Models.Task t = new MyApp.Models.Task();Quick practice
Section titled βQuick practiceβ-
What problem do namespaces primarily solve?
Answer
Naming collisions β they let two types with the same short name coexist in a codebase as long as they live in different namespaces. -
What does a
usingdirective do?Answer
Brings a namespace's types into scope so you can reference them by their short name instead of the fully-qualifiedNamespace.TypeNameform. -
Whatβs a file-scoped namespace, introduced in C# 10?
Answer
A namespace declared withnamespace MyApp.Utilities;(no braces) that applies to everything in the rest of the file, saving one level of indentation compared to the traditional brace-block form.