Define namespaces
The definition of a namespace begins with the keyword namespace, followed by the name of the namespace, as follows:
namespace Namespace_name {//code declaration}
In order to invoke a function or variable that supports the namespace version, the name of the namespace is placed in front, as follows:
Namespace_name.item_name;
The following program demonstrates the use of namespaces:
Using System;namespace first_space{class Namespace_cl {public void Func () {Console.WriteLine ("Inside First_space");}} }namespace second_space{class Namespace_cl {public void Func () {Console.WriteLine ("Inside Second_space");}}} class Te stclass{static void Main (string[] args) {FIRST_SPACE.NAMESPACE_CL fc =new first_space.namespace_cl (); second_ SPACE.NAMESPACE_CL sc = new SECOND_SPACE.NAMESPACE_CL (); Fc.func (); Sc.func (); Console.readkey (); }}
When the above code is compiled and executed, it produces the following results:
Inside first_space Inside Second_space
Using keyword
The Using keyword indicates that the program is using a name in the given namespace. For example, we use the System namespace in our programs, where class Console is defined. We can write only:
Console.WriteLine ("Hello There");
We can write the fully qualified name as follows:
System.Console.WriteLine ("Hello there");
You can also use a using namespace directive so that you do not have to precede the namespace name when you use it. The directive tells the compiler that subsequent code uses the name in the specified namespace. The following code demonstrates the application of namespaces.
Let's use the using specification to override the above instance:
Using system;using first_space;using Second_space;namespace first_space{class ABC {public void func () {Console.writelin E ("Inside first_space"); }}}namespace second_space{class EFG {public void Func () {Console.WriteLine ("Inside Second_space");}}} class Testclas s{static void Main (string[] args) {ABC FC = new ABC (); EFG sc = new EFG (); Fc.func (); Sc.func (); Console.readkey (); }}
When the above code is compiled and executed, it produces the following results:
Inside first_space Inside Second_space
Nested namespaces
Namespaces can be nested, meaning that you can define another namespace within one namespace, as follows:
namespace Namespace_name1 {//Code declaration namespace Namespace_name2 {//code declaration}}
You can use the dot (.) operator to access the members of a nested namespace, as follows:
Using system;using first_space;using First_space.second_space;namespace first_space{class ABC {public void func () {Cons Ole. WriteLine ("Inside first_space"); }} namespace Second_space {class EFG {public void Func () {Console.WriteLine ("Inside Second_space");}}} Class testclass{static Voidmain (string[] args) {ABC FC = new ABC (); EFG sc = new EFG (); Fc.func (); Sc.func (); Console.readkey (); }}
When the above code is compiled and executed, it produces the following results:
Inside first_space Inside Second_space