C Sharp Namespaces

C# Namespaces

To easily handle an application, too many classes are organized in C# using the Namespaces. The System.Console is used in a simple C# program. Here, System is the namespace and Console is the class. The namespacename.classname can be used to access the class of a namespace. To not use the complete name all the time, the using keyword can be used. The global namespace in C# is the root namespace. The namespace “System” of .Net Framework is referred by the global::System always.

Example:

using System;  
namespace Example  
{  
    class Hello  
    {  
        static void Main(string[] args)  
        {  
            Console.WriteLine("Hello World!!");  
        }  
    }  
}

Output:

Explanation:

In the above example, we are using the namespace in C#. Here, the namespace contains one class “Hello”.

C# namespace: by fully qualified name:

Example:

using System;  
namespace Name1 {  
public class Example  
{  
    public void Name() { Console.WriteLine("First Name"); }  
}  
}  
namespace Name2  
{  
    public class Example  
    {  
        public void Name() { Console.WriteLine("Last Name"); }  
    }  
}  
public class TestNamespace  
{  
    public static void Main()  
    {  
        Name1.Example n1 = new Name1.Example();  
        Name2.Example n2 = new Name2.Example();  
        n1.Name();  
        n2.Name();  
 
    }  
}

Output:

Explanation:

In the above example, we are displaying the use and behaviour of using the namespace in C#. Here, a namespace program accesses another namespace program.

C# namespace: Using keyword:

Example:

using System;  
using Name1;  
using Name2;  
namespace Name1 {  
public class First  
{  
    public void firstName() { Console.WriteLine("First Name"); }  
}  
}  
namespace Name2  
{  
    public class Last  
    {  
        public void lastName() { Console.WriteLine("Last Name"); }  
    }  
}  
public class TestNamespace  
{  
    public static void Main()  
    {  
        First n1 = new First();  
        Last n2 = new Last();  
        n1.firstName();  
        n2.lastName();  
    }  
}

Output:

Explanation:

In the above example, we are displaying the use and behaviour of using the “using” keyword with namespace in C#. Thus, here, the complete name is not required for accessing a namespace program. The output of the class inside both the namespace will be displayed on the screen on execution.

Please follow and like us:
Content Protection by DMCA.com