Using namespaces

A namespace is a logical construct for grouping related things across one or more physical files. Unlike a class, namespaces can not be instantiated. Namespaces create a domain in which definitions and declarations (from this point we use the term Identifiers) live. Items are unique within a namespace, so you can not repeatedly define the same construct, or declare the same variable. A good example of this at the micro-level is a function. When you define a function, you can declare a variable only once within the scope of that function. A namespace's scoping rules operate exactly the same as the function except that the Identifier may be referenced from within other namespaces. With this in mind, it should be clear that namespaces allow you to define the same construct, or declare a variable with the same name, repeatedly in different namespaces but not repeated within the namespace.

Namespaces are created the keyword namespace. anything declared/defined within the namespace is owned by the namespace.

Identifiers can be referenced using the fully qualified name, consider the following piece of code

The class MyClass is defined within the namespace "container" at line 7. It is then referenced at line 18 using its fully qualified name container.MyClass.

You may have several Items within a namespace that you need to reference. The above approach of prefixing the Identifiers with the namespace can be very tedious. The shorthand approach is to tell the compiler that all the Items within a namespace are required in the current namespace. This is done through the use of the using keyword.

On line 13 we introduce the use of the using keyword. Line 19 has now been simplified. We no longer need to qualify the Identifier with its namespace since the namespaces has been introduced into the current namespace with the using keyword.

Identifier Resolution

Consider the block of code

We introduce the container namespace into the csharp_app_struture namespace at line 13

The using keyword must be before any declarations and definitions within a namespace

Within the csharp_app_struture namespace there are now two Person classes available. When you run this program it will print the value 33. The C# compiler resolves to the last seen definition. So the Person definition at line 14 overrides that seen in line 5.

It’s normal practice to organise your namespaces into separate files or within the same file as shown in the example above