![]() |
VOOZH | about |
In C#, a namespace is a way to organize and group related classes, interfaces, structs and other types. It helps avoid name conflicts and makes code easier to manage, especially in large projects.
To define a namespace in C#, we will use the namespace keyword followed by the name of the namespace and curly braces containing the body of the namespace as follows:
namespace name_of_namespace {
// Namespace (Nested Namespaces)
// Classes
// Interfaces
// Structures
// Delegates
}
The members of a namespace are accessed by using dot(.) operator. A class in C# is fully known by its respective namespace.
[namespace_name].[member_name]
Note:
Example:
Hello Geeks!
In the above example:
In C#, calling a class or function with its fully qualified name (namespace + class) every time is not practical.
For example:
System.Console.WriteLine("Hello Geeks!");
first.Geeks_1.display();
To avoid this, C# provides the using keyword. By adding using at the top of the program, you can access the classes and methods of that namespace directly, without writing the full name each time.
using [namespace_name][.][sub-namespace_name];
In the above syntax, dot(.) is used to include subnamespace names in the program.
Program to illustrate the use of using keyword
Output:
Hello Geeks!
You can also define a namespace into another namespace which is termed as the nested namespace. To access the members of nested namespace user has to use the dot(.) operator.
For example: Generic is the nested namespace in the collections namespace as System.Collections.Generic
namespace name_of_namespace_1
{
// Member declarations & definitions
namespace name_of_namespace_2
{
// Member declarations & definitions
.
.
}
}
Program:
Nested Namespace Constructor