C#-Namespaces

About Namespaces in detail

C#-Namespaces declare a scope that contains a set of related objects. You can use a namespace to organize code elements. You can define your own namespaces and use them in your program.

In C#, global namespace is the root namespace. The global::System will always refer to the namespace “System” of .Net Framework.


Example :

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

namespace example : by fully qualified name:

using System;
namespace First {
public class Hello
{
    public void sayHello() { Console.WriteLine("Hello First Namespace"); }
}
}
namespace Second
{
    public class Hello
    {
        public void sayHello() { Console.WriteLine("Hello Second Namespace"); }
    }
}
public class TestNamespace
{
    public static void Main()
    {
        First.Hello h1 = new First.Hello();
        Second.Hello h2 = new Second.Hello();
        h1.sayHello();
        h2.sayHello();

    }
}

namespace example : by using keyword

The using keyword states that the program is using a given namespace.

using System;
using First;
using Second;
namespace First {
public class Hello
{
    public void sayHello() { Console.WriteLine("Hello Namespace"); }
}
}
namespace Second
{
    public class Welcome
    {
        public void sayWelcome() { Console.WriteLine("Welcome Namespace"); }
    }
}
public class TestNamespace
{
    public static void Main()
    {
        Hello h1 = new Hello();
        Welcome w1 = new Welcome();
        h1.sayHello();
        w1.sayWelcome();
    }
}

Recommended Posts:

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *