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 Item) 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 Item 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.
Items can be referenced using the fully qualified name, consider the following piece of code
The variable x
is declared within the namespace "container
" at line 7. It is then referenced at line 18 using its fully qualified name container.MyClass.x
.
You may have several Items within a namespace that you need to reference. The above approach of prefixing the Items 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 Item with its namespace since the namespaces has been introduced into the current namespace with the using
keyword.
Add Comment