Namespaces

These are defined in files, organized by namespaces, compiled into a module, then grouped into an assembly. These organizational units are cross-cutting. For example, typically a group of namespaces belong to one assembly, but a single namespace may in fact be spread over multiple assemblies.

Files

File organization is almost of no significance to the C# compiler—a whole project could be merged into one .cs file and it would still compile (preprocessor statements are the only exception to this). However, it’s generally tidy to have one type in one file, with the filename matching the name of the class and the file’s directory matching the name of the class’s namespace.

Using Namespaces

A namespace lets you group related types into a hierarchical categorization. Generally, the first name is the name of your organization; it gets more specific from there:

namespace MyCompany.MyProduct.Drawing {
  class Point {int x, y, z;}
  delegate void PointInvoker(Point p);
}

Nesting namespaces

You may also nest namespaces instead of using dots. This example is semantically identical to the previous example:

namespace MyCompany {
  namespace MyProduct {
    namespace Drawing {
      class Point {int x, y, z;}
      delegate void PointInvoker(Point p);
    }
  }
}

Using a type with its fully qualified name

To use the Point from another namespace, you may refer to it with its fully qualified name. The namespace that a type is within actually becomes part of the type name:

namespace TestProject { class Test { static ...

Get C# Language Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.