C# Namespaces
In this chapter you will learn:
Description
A namespace is a domain within which type names must be unique.
Types are typically organized into hierarchical namespaces to avoid naming conflicts and to make type names easier to find.
Example
For example, the RSA type that handles public key encryption is defined within the following namespace:
System.Security.Cryptography
A namespace forms an integral part of a type's name. The following code calls RSA's Create method:
System.Security.Cryptography.RSA rsa = System.Security.Cryptography.RSA.Create();
namepace keyword
The namepace keyword defines a namespace for types within that block.
For example:
namespace Outer.Middle.Inner/*www . j a va2s . co m*/
{
class Class1 {}
class Class2 {}
}
The dots in the namespace indicate a hierarchy of nested namespaces. The code that follows is semantically identical to the preceding example:
namespace Outer /*from ww w .j a v a 2 s. com*/
{
namespace Middle
{
namespace Inner
{
class Class1 {}
class Class2 {}
}
}
}
We can refer to a type with its fully qualified name, which includes all namespaces from the outermost to the innermost. For example,
Outer.Middle.Inner.Class1;
Outer.Middle.Inner.Class2;
Example 2
C# uses dot to indicate the namespace hierarchy. The following two code blocks have the same namespaces.
namespace A.B.C{/*from www. j a v a 2 s. co m*/
}
namespace A{
namespace B{
namespace C{
}
}
}
Next chapter...
What you will learn in the next chapter:
- What is namespace using Directive
- Example for C# namespace using Directive
- using statement and namespace
- Namespaces prevent name conflicts