Home » .Net

Namespaces in C#

In this article, we are going to learn about Namespaces in C#. What is Namespace, how to use Namespace in the program? Learn with Examples.
Submitted by IncludeHelp, on August 11, 2018

C# Namespace

In C# namespaces are used to group similar type of classes. Two classes with same name in different namespaces never conflict to each other.

In C# namespace can be:

  • User defined
  • Pre defined, that is in-built in .NET class library

Here, we need to use using keyword to access defined namespaces.

Syntax:

namespace <namespace_name>
{
	//Write code here
}

Note:

  • To declare user defined namespace we need to use namespace keyword.
  • If we want to access class defined inside namespace then we need use . (dot) Operator.

Example:

using System;
using System.Collections;

namespace namespace1
{
    class ABC
    {
        public void fun()
        {
            Console.WriteLine("Inside Namespace1");
        }
    }
}

namespace namespace2
{
    class ABC
    {
        public void fun()
        {
            Console.WriteLine("Inside Namespace2");
        }
    }
}    
    
class Program
{
    static void Main()
    {
        namespace1.ABC OB1 = new namespace1.ABC();
        namespace2.ABC OB2 = new namespace2.ABC();

        OB1.fun();
        OB2.fun();

    }
}

Output

    Inside Namespace1
    Inside Namespace2

Read more: The 'using' Keyword in C#, Nested Namespace in C#



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.