Namespaces

These are defined in files, organized by namespaces, compiled into a module, then grouped into an assembly.

These organizational units are crosscutting. For example, typically a group of namespaces belong to one assembly, but a single namespace may in fact be spread over multiple assemblies (see Chapter 12).

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 directory the file is in matching the name of the class’s namespace.

Namespaces

namespace name+           // Dot-delimited
{
 using-statement*
 [namespace-declaration | 
  type-declaration]*      // No delimiters
}

A namespace lets you group related types into a hierarchical categorization. Generally the first name is the name of your organization, and 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 ...

Get C# in a Nutshell 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.