Skip to content

Namespaces

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.

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 file
namespace MyApp.Utilities;
public class Helper { }
// Fully-qualified name, used when two namespaces have a colliding type name
var user = new MyApp.Models.User();

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 them
MyApp.Models.Task t = new MyApp.Models.Task();
  1. What problem do namespaces primarily solve?

    AnswerNaming collisions β€” they let two types with the same short name coexist in a codebase as long as they live in different namespaces.
  2. What does a using directive do?

    AnswerBrings a namespace's types into scope so you can reference them by their short name instead of the fully-qualified Namespace.TypeName form.
  3. What’s a file-scoped namespace, introduced in C# 10?

    AnswerA namespace declared with namespace 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.